First of all, here comes the load part.
Structure MainStruct
Dim Ans1 As String
Dim Ans2 As String
End Structure
Dim Build As New List(Of MainStruct)
...
...
...
Session("MyData") = Build
The question is how can i read back the contents of the list, stored in the Session?
I mean something like...
Build = Session("MyData")
Instead of Build = Session("MyData").Ans1 you will want to do
Build = CType(Session("MyData"), List(Of MainStruct))
You could also do a DirectCast instead of CType if you want.
Edit: to question change
To then read back the results you will be able to go through Build.
You could loop through it with a for each, a for, some linq, whatever you want!
Since its VB i dont think u need to cast it back, correct me if im wrong.
i dont think u can just do
Build = Session("MyData").Ans1
You need to do something like:
Build = Session("MyData")
then u iterate though ur List<> to access the structs
Related
I have a directory of Xml files. How do I grab only the files that have been created in the last 30 days and sort them in ascending order? I am not bound to using Directory.GetFiles if there is a more efficient solution.
I then create and bind a list of files to a gridView in which I need both the File Name and Path. I display the File Name and use the Path value in the RowDataBound event to build a HyperLink to the file.
Thanks! \m/ \m/
Dim filePaths() As String = Directory.GetFiles("C:\XmlFiles\")
Dim files As List(Of ListItem) = New List(Of ListItem)
For Each filePath As String In filePaths
files.Add(New ListItem(Path.GetFileName(filePath), filePath))
Next
gv.DataSource = files
gv.DataBind()
We can do a little better. Just getting the names and then sorting by time afterwards requires separate trips out the hard drive for both attributes, which is slow. By switching to DirectoryInfo, we can reduce this to one trip to disk per file:
Dim filesByDate = DirectoryInfo.EnumerateFiles("C:\XmlFiles\").
Where(Function(f) f.CreationTime > DateTime.Today.AddDays(-30)).
OrderBy(Function(f) f.CreationTime).
Select(Function(f) f.Name)
gv.DataSource = filesByDate
gv.DataBind()
Not that the difference is likely to drive your program's performance, but it's always nice to reduce disk I/O :)
This is also a case where it might be better to use GetX instead of EnumerateX. Generally, you want to prefer anything that will "enumerate" vs "get", because of the reduced memory use and the ability to start processing as soon as the first item is available, instead of waiting until the last item is available. In this case, though, there's a chance that you can trade memory use for disk I/O. I'm not familiar with the internal implementation of the methods, but it may be possible for GetFileSystemInfos() to get the information for all of the files in one or a few trips to disk, and that would be a big win. But again... I'm not familiar with the details here; you'd have to test for yourself which is better in your situation.
You can use LINQ:
Dim filePathsSortedByDate = From f In Directory.EnumerateFiles("C:\XmlFiles\")
let fileCreationTime = File.GetCreationTime(f)
Where (Date.Today - fileCreationTime.Date).Days <= 30
Order By fileCreationTime
Select New ListItem(Path.GetFileName(f), f)
Dim files As List(Of ListItem) = filePathsSortedByDate.ToList()
I have a stored procedure that I'm calling from asp.net and I'm adding 47 parameters mostly from values selected on drop downs and radio buttons and text boxes from a form. I also have (for some reason beyond my pay grade) some parameters that are set to Null..these are also a source of some hair pulling and I don't know if these are the problems or not.
Dim Parameter As SqlParameter = New SqlParameter("#type", "u")
Dim Parameter1 As SqlParameter = New SqlParameter("#user", User)
Dim Parameter2 As SqlParameter = New SqlParameter("#term", terminal)
Dim Parameter3 As SqlParameter = New SqlParameter("#url", accesslevel)
Dim Parameter4 As SqlParameter = New SqlParameter("#name", firstname & " " & lastname)
Dim Parameter5 As SqlParameter = New SqlParameter("#mgr", mgr)
Dim Parameter6 As SqlParameter = New SqlParameter("#mgrEmail", mgr)
Dim Parameter7 As SqlParameter = New SqlParameter("#phone", mgr)
Dim Parameter8 As SqlParameter = New SqlParameter("#title", titletitle)`
... and on and on until Parameter48...
Dim myCommand As New SqlCommand("dbo.proc_vsSpacAccess", conn)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.Add(Parameter)
myCommand.Parameters.Add(Parameter1)
myCommand.Parameters.Add(Parameter2)
myCommand.Parameters.Add(Parameter3)
myCommand.Parameters.Add(Parameter4)
... and on until Parameter48... and then finally I run the stored proc..
myCommand.ExecuteNonQuery()
end of subroutine...
I run this and get nothing, no feedback, nothing. How do I know what's wrong if things aren't working? do I debug from SQL Server (I can't change the stored procedure it's not mine to change btw) or try to debug the stored procedure from Visual Studio?
I REPEAT, I CANNOT CHANGE THE STORED PROCEDURE IT IS READ ONLY FOR ME..
ExecuteNonQuery won't return anything unless you explicitly catch the return value.
If you want to know how query is executing, you can view using SQL Server Profiler.
Set a break point right after ExecuteNonQuery
Let SQL Server Profiler run at the background
See the executed query
You can even copy the query from Profiler, and run it in SSMS to make sure it even works.
Let me give you some advice on debugging. First run profiler when you run your application (on dev!) and grab the SQL that is generated.
Next open up SSMS and put that SQL in it and see if it generated valid sql. Sometimes you qwill find it did not. Then the problem is in how you are building the sql. If the SQL is valid, either it ran but didn't give you a return message or the problem is the proc itself or the data in the parameters.
Then open up the stored proc to see what it does; if it is inserting to a table or updating a table, check that table in the db to see if the data was inserted or updated based on teh variables you sent. You should always have unit tests built to check the results of an action stored proc, if you do not, then write them now, so the next time you test, you know what you should see in the database as a result of running the proc.
If you did not get the action you expected, try running the proc from SSMS with the profiled data. If the data still doesn't insert or update, you may need to ask the people responsible for the proc to track down what the problem is. Likely in this case, soemthing is wrong with the particular parameters you are sending although it could bea genuiine bug of a case taht was not expected. For instance you may be sending a null for a reuired field. Not all procs are built to properly handle errors, so it may not be sending one up the chain to you.
Lets start from the point that when it comes to executing stored procedures, you need to design it to return some feedback. Just the fact that you have stored procedure, doesn't mean that you will have any feedback. For example (pseudo-code)
Create procedure MyProc()
Begin
Try
-- Do something
-- And it happens to error here
Catch
' do nothing
End Try
End
Now, this one, will never give you any info of what happened, success or failure because error is handled within
Lets look at this one now, again, pseudo-code
Create procedure MyProc(#retVal int out)
Begin
set #retVal = -1 -- assume it failed
Try
-- Do something
set #retVal = 0 -- a flag that it is success
Catch
' do nothing
End Try
End
Now, with this you can go to your vb code and test
myCommand.ExecuteNonQuery()
Dim val as Object = myCommand.Parameters(0).Value
If CInt(val) = 0 Then
' success route
Else
' error route
End If
Basically, this is the example of one of the few methods how to obtain info about state of execution of your stored procedure. But again, you need to code for this.
Now, if you want to know in details, what is your SP doing while it is executing, again, you need to code for this. You can create a log table, in which you will store data that you scrape within your SP. I've seen designs where each SP had one parameter #debug. And, when called in debug mode, it would post logs about its execution data.
I've googled but none of the solutions seems to work for me!
I have a SPROC in SQL Server which has an input param and also an output parameter being set within the SPROC.
using classic ASP, I want to retrieve the value of that output parameter but nothing seems to get set (but I can see the output parameter working correctly when executing in the SQL Server Management Studio)
OpenConnection
Set cmdTemp = Server.CreateObject("ADODB.Command")
cmdTemp.CommandType = 4 'adCmdStoredProc
Set cmdTemp.ActiveConnection = dbConn
cmdTemp.CommandText = "GetCerts"
cmdTemp.Parameters.Refresh
cmdTemp.Parameters(1) = "ABC123"
cmdTemp.Parameters(2).Direction = 2 'Output
Set reader = cmdTemp.Execute
Response.Write(cmdTemp.Parameters(2)) ' Nothing is displayed at all.
CloseConnection
I tried using the named parameters approach but always got an error saying that the parameters are out of range, wrong arguments or wrong type (Something similar to this).
Really... getting a headache. I just want the OUTPUT param value set from the SPROC (2nd parameter in the SPROC)
Check for errors:
Set reader = cmdTemp.Execute
If Err.number <> 0 or dbConn.Errors.Count <> 0 Then
'Do something to handle the error
End If
Do you have permissions to execute the stored procedure? i.e. the credentials of the ASP user...
Execute Stored Procedure from Classic ASP
It seems after a long long investigation that what I am trying to do is not possible (but it is in .NET). Seems I need to execute the command twice, first time getting the output parameters values then the next time to display the results. Awful. Praise .NET!
Most collections in the COM world use zero-based indexing. Try using Parameters(0) as the input parameter and Parameters(1) as the output parameter.
I need to be able to handle an HTML encoded ampersand in my .Net code.
So the Url is
http://myite.com/index.aspx?language=en&Refresh=true
There is no way of changing this as it has been generated by something else so this is out of my control.
How can I read the Refresh parameter?
I have tried
HttpUtility.UrlDecode(Request.QueryString("Refresh"))
but my Request.QueryString("Refresh") is actually empty, so this is pointless, as is Uri.EscapeDataString.
This can't be the first time this has happened, but I'm struggling to find a solution, as most people would say use UrlEncoding, but as I said, the Url is out of my control.
& in your query string should be %26.
Since you can't correct the url.
You can read the refresh value as:
Request.QueryString("amp;Refresh");
Note that the developer of the service you are using may correct this in future.
It would be good to be ready for that already.
var refresh = Request.QueryString("amp;Refresh");
if(String.IsNullOrEmpty(refresh))
refresh = Request.QueryString("Refresh");
nunespascal answer pretty much solves your problem. There are some alternate methods.
If its guaranteed that your Refresh parameter is the second key in the QueryStringCollection then you can use Request.QueryString(1)
Another method is to do a Contains on the QueryStringCollection.
If Request.QueryString IsNot Nothing AndAlso Request.QueryString.AllKeys.Count() > 0 Then
Dim refreshKey = Request.QueryString.AllKeys.FirstOrDefault(Function(nv) nv.Contains("Refresh"))
If refreshKey IsNot Nothing Then
Dim refreshValue = Request.QueryString(refreshKey)
End If
End If
I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.
I have an array of imagefile paths, like so:
dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"
This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).
If Not banners Is Nothing then
' then loop through the Dictionary and make a list of image links
End if
The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error
What's the proper way to check if an object exists in VB Script?
#Atømix: Replace
If Not banners Is Nothing then
and use
If IsObject(banners) Then
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
#Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)
IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised.
To summarize:
IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised
IsNull(var) will test if a variable has been assigned to Null
var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object
IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty).
If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function:
Dim banners
If IsEmpty(banners) Then
Response.Write "Yes"
Else
Response.Write "No"
End If
' Should result in "Yes" being written
banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing.
You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems.
edit: I just saw this related question and answer which might help, too.
Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this:
Sub FooBar(Optional oDoc As Object)
'if parameter is missing then simulate it
If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something
...
You need to have at least dim banners on every page.
Don't you have a head.asp or something included on every page?
Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered.
The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here:
Is there any way to check to see if a VBScript function is defined?