VB.NET Asynchronous Task keeping HttpContext - asp.net

I'm using .NET Framework 4.0.
I have a function that creates and calls a Task. In some part of its process I need a value stored in the Session, but it returns Nothing because the Task doesn't have the HttpContext.
Here's an example:
Public Class Example
Inherits System.Web.Mvc.Controller
<AcceptVerbs("GET", "POST")>
Public Sub DoSomething()
Dim products As List(Of Product)
Dim something As New Task(Sub()
For Each product In products
product.Name = product.Name.ToUpper
product.Save()
Next
End Sub)
something.Start()
End Sub
End Class
Public Class Product
Public Sub OnProductSave()
Dim session = Web.HttpContext.Current.Session
Dim log As New Log()
log.UserId = session("UserId")
log.Date = DateTime.Now()
log.Save()
End Function
End Class
There is a way that I could use the HttpContext in the Task?
Obs.: In the example I could pass the value of UserId to the function, but in the real case it's more complex than that.
Obs.2: I know that I could create a variable with the value of HttpContext and after set it to the Task's HttpContext, but I think there could be a better way. :)

Related

How to store cache in cefsharp version 79

I am using cefsharp in my Winform application. I try to store cookies, cache... so that I do not have to login a web site each time I run my application.
I try to implement as follows:
Dim requestContextSettings = New RequestContextSettings()
requestContextSettings.CachePath = Application.StartupPath + "\Resources"
_browser = New ChromiumWebBrowser("https://cookies_enabled_web.com", New RequestContext(requestContextSettings, New CustomRequestContextHandler()))
Then I implement the class
Public Class CustomRequestContextHandler
Implements IRequestContextHandler
Public Sub OnRequestContextInitialized(requestContext As IRequestContext) Implements IRequestContextHandler.OnRequestContextInitialized
Exit Sub
End Sub
Public Function OnBeforePluginLoad(mimeType As String, url As String, isMainFrame As Boolean, topOriginUrl As String, pluginInfo As WebPluginInfo, ByRef pluginPolicy As PluginPolicy) As Boolean Implements IRequestContextHandler.OnBeforePluginLoad
Return True
End Function
Public Function GetResourceRequestHandler(browser As IBrowser, frame As IFrame, request As IRequest, isNavigation As Boolean, isDownload As Boolean, requestInitiator As String, ByRef disableDefaultHandling As Boolean) As IResourceRequestHandler Implements IRequestContextHandler.GetResourceRequestHandler
Return Nothing
End Function
End Class
But it does not work as expected?
Does anyone know how to fix the problem?
Any help would be appreciated.
Finally, I have successfully stored cache data in Cefsharp version 79. I execute the following code before create the instance of browser.
Dim setting As New CefSettings()
setting.CachePath = Path.Combine(Application.StartupPath, "Resources")
CefSharp.Cef.Initialize(setting)

Property binding to web controls in asp.net with linq and reflection

I'd like to "bind" properties from a DTO to corresponding controls, for example checkboxlists or textboxes. This is so that I can use a dto (passed through the querystring) to set the initial state of the control, and then have the control set it's value to the dto when it comes time to leave the page. I could do this with two mapping functions (control->DTO, DTO->Control) but instead I'm using Linq and Reflection to maintain a list of property<->control relationships.
I've never done this before and I suspect there may be a better way ... how would you maintain a property<->control relationship?
Here is the code I've used:
Public Class ObjectPropertyMapper
''' <summary>Provides a binding of a control to one or more properties in a DTO.</summary>
Private Class ControlBinding
''' <summary>A reference to the control which will be bound.</summary>
Public Property Control As Control
''' <summary>The property(ies) which the control will be bound to.</summary>
Public Property Props As New List(Of PropertyInfo)
Public Sub New(ctrl As Control, props As IEnumerable(Of PropertyInfo))
Me.Control = ctrl
Me.Props.AddRange(props)
End Sub
End Class
''' <summary>A list of all the control to dto bindings for this page.</summary>
Private Property ControlBindings As New List(Of ControlBinding)
''' <summary>Returns the property info from a linq expression.</summary>
Private Function GetPropertyFromExpression(Of T)(linqExpression As System.Linq.Expressions.Expression(Of Func(Of T))) As PropertyInfo
If TypeOf linqExpression.Body Is MemberExpression Then
Return DirectCast(linqExpression.Body, MemberExpression).Member
Else
Dim op = (CType(linqExpression.Body, UnaryExpression).Operand)
Return DirectCast(op, MemberExpression).Member
End If
End Function
''' <summary>Binds a control to a single property of the DTO.
''' Usage: BindControlToProperty(cblFundTypes, Function() Me.SearchParams.FundTypeIDs) ... </summary>
Protected Overloads Sub BindControlToProperty(Of T)(ctrl As Control, linqExpression As System.Linq.Expressions.Expression(Of Func(Of T)))
' This works by passing through a linq expression, which in turn has a reference to the property.
' We can therefore extract the property from the linq expression, allowing us to store a reference to the property against the reference to the control
Dim prop As PropertyInfo = GetPropertyFromExpression(linqExpression)
ControlBindings.Add(New ControlBinding(ctrl, {prop}))
End Sub
End Class
And the consumer:
Public Class MyPage
Public Sub OnLoad
BindControlToProperty(myCheckBoxList, Function() MyDTO.IntListProperty)
End Sub
End Class
The only alternate method I found was projecting properties onto an anonymous type, as per https://stackoverflow.com/a/1984190/767599
An example would be:
Public Class exampleDTO
Public Property MyProp1 As String
Public Property MyProp2 As String
End Class
Public Function GetVariableName(Of T)(obj As t) As String
Dim properties As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
If properties.Length = 1 Then
Return properties(0).Name
Else : Throw New Exception
End If
End Function
Public Sub BindToControl(Of T)(ctrl As Control, prop As T)
Response.Write(GetVariableName(prop))
End Sub
Public Sub Main
Dim c As New Control
Dim dto As New exampleDTO
BindToControl(c, (New With {dto.MyProp1}))
End Sub
However I have no idea which solution is "better".

Same Function Running Parallel will override values?

I am Using same function from many places...
for example below function
Public Sub getUser(ByVal Name as string)
dim myName=Name
.......
insert(myName)
End Sub
I am using this function from so many places...
I have doubt should this function override this myName values with latest function call?
Suppose i called getUser("ABC") so value of myName is now ABC now sudden all call getUser("XYZ") so at insert(myName) will it insert("ABC") or insert("XYZ")??
I need it to be insert("ABC") and then insert("XYZ")
You can use locking to make sure only one thread does something at a time
//declare an object for locking
Dim lockObjcect As New [Object]()
Public Sub getUser(ByVal Name as string)
SyncLock lockObjcect
dim myName=Name
.......
insert(myName)
End SyncLock
End Sub
With the locking, now only one thread will be able to execute the code between SyncLock and End SyncLock this means First ABC will be inserted and then XYZ will be inserted

vb.net Web Server linq to sql returns

My last question was not clear. Im trying to make a web service in VB.net is their a way that i can return the results that i get from LINQ. ie "return objreturnLINQResults"
I have tryed to set my Public Function GetAlarmsByGUIS(ByVal DeptGUID As String, ByVal IdNumber As String) As Linq.DataContext . i just keep getting errors. help please.
Public Function GetAlarmsByGUIS(ByVal DeptGUID As String, ByVal IdNumber As String) As Linq.DataContext
Dim lqAlarms As New linqAlarmDumpDataContext
Dim Temp As String = ""
Dim n As Integer = 0
Dim GetAlrms = From r In lqAlarms.AlarmDrops _
Where r.DeptGUID = DeptGUID And Not r.AlarmsHandled.Contains(IdNumber) _
Order By r.TimeDate Descending _
Select r
Return GetAlrms
End Function
1) You can't create web service's method which returns DataContext object.Return values and input parameters of Web service methods must be serializable through the XmlSerializer class. DataContext is not serializable
2) The simplest way to avoid errors it is return an array of serializable objects. Like this Return GetAlrms.ToArray();

Calling a Class in ASP.NET

I know my ASP.NET but i have to admit, i am dumb with classes and not sure how they work exactly. Also have not worked with them yet but i want to. But what I do know is that it's a place where i can keep code for re-use correct? How will my class look with my code?
So this is my code i use on about 3 forms - but i want to save it in 1 spot and just call it from like when i click on btnSubmit.
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As SqlConnection = New SqlConnection(strConnection)
Dim cmd As SqlCommand = New SqlCommand
Dim objDs As DataSet = New DataSet
Dim dAdapter As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT distinct FIELD FROM TABLE order by FIELD"
dAdapter.SelectCommand = cmd
con.Open()
dAdapter.Fill(objDs)
con.Close()
If (objDs.Tables(0).Rows.Count > 0) Then
lstDropdown.DataSource = objDs.Tables(0)
lstDropdown.DataTextField = "FIELD"
lstDropdown.DataValueField = "FIELD"
lstDropdown.DataBind()
lstDropdown.Items.Insert(0, "Please Select")
lstDropdown2.Items.Insert(0, "Please Select")
Else
lblMessage.Text = "* Our Database seem to be down!"
End If
What must i put here to execute my code above?
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
?????????????????????????????????
End Try
End Sub
Etienne
A class is (in VB.Net) is defined as so
Public Class Person
private _firstName as string
private _lastName as string
'''Constructor with no params
public Sub New()
_firstName = ""
_lastName = ""
End Sub
'Contructor with params
Public Sub New(FirstName as String, LastName as String)
_firstName = FirstName
_lastName = LastName
End Sub
Public Property FirstName As String
Get
return _firstName
End Get
Set(value as String)
_firstName = value
End Set
End Property
Public Property LastName As String
Get
return _lastName
End Get
Set(value as String)
_lastName = value
End Set
End Property
Public Function HitHomeRun() As Boolean
....'Do some stuff here
End Function
End Class
You can then instantiate the class and call its members.
Dim p as New Person()
p.FirstName = "Mike"
p.LastName = "Schmidt"
dim IsHomeRunHit As Boolean = p.HitHomeRun()
Learn more about creating and consuming classes in VB.Net.
This is a very big topic and can be defined in many different ways. But typically what you are venturing into is an N-Tier architecture.
Data Access Layer
Business Logic
UI Logic
Now the way a class can be built in your question can be done, but in the long run is prone to maintenance horror and modifiiability is cut short. Not to mention very much prone to bugs. Putting any type of data access code in your UI layer is bad practice.
This is where the power of having separate layers of classes (separation of concerns) in each layer gives you the ability to reuse code and ability to easily modify for future expansions/features etc. This is getting into Software Architecture is a very broad topic to put into one post.
But if you are really interested here are some links to point you into the right directions.
N-Tier Architecture from Wikipedia
Data Access Layer
Business Logic Layer
Martin Fowler is an expert in Architecture
There is software that eases the pain of the DAL.
1. Linq-To-SQL ability to query your data via .Net Objects (compiled queries)
2. Entity Framework Version 2 of Linq-To-SQL
And this effectively could replace all of your SQL code.
If you want to reuse the code, you should put it in a separate project. That way you can add that project to different solutions (or just reference the compiled dll).
In your web project you add a reference to the project (or to the dll if you have compiled it before and don't want to add the project to the solution).
In your new project you add a class file, for example named UIHelper. In the class skeleton that is created for you, you add a method. As the class is in a separate project, it doesn't know about the controls in the page, so you have to send references to those in the method call:
Public Shared Sub PopulateDropdowns(lstDropdown As DropDownList, lstDropdown2 As DropDownList)
... here goes your code
End Sub
In your page you call it with references to the dropdown lists that you have in the page:
UIHelper.PopulateDropdowns(lstDropdown, lstDropdown2)
This will get you started. There is a lot more to learn about using classes...
I sometimes create a "Common" class and put public Shared methods in it that I want to call from different places.
Something along these lines:
Public Class Common
Public Shared Sub MyMethod
'Do things.
End Sub
End Class
I'd then call it using:
Common.MyMethod
Obviously, you can a sub/function definition that takes the parameters you require.
Sorry if my VB.NET code is a bit off. I usually use C#.
I think you should look into using visual studio designer tools to do your data access and data binding. Search for typed datasets

Resources