Format SQL Query Result into web menu - javascript

I am trying to bhuild a drill down menu for my website, where user will click on a category and it will show the subcategories of that clicked category, there could be n-levels.
I am able to write sql query which returns the output exactaly as I want, but the problem is...I dont want to show the whole menu to end user, I would like to open/expand only clicked category.
my Query output is:
1 IPTV
2 Jadoo Tv
3 Shava Tv
4 Jalva Tv
5 Programming
6 Microsoft
7 Asp.Net
8 PHP
so by default IPTV & Programming Should be displayed, since they are parent, and when I click on IPTV it should open the children of IPTV, like I said there could be n-levels.
I was thinking, I can load the output of query to webpage and then control the menu navigation with css/javascript.
do you guys have any ideas?

ok, here is the complete code for markup (after I get the result from sql sp).
Private Sub CreateLeftMenu()
Dim dt As DataTable = DAL.ReturnMSSQLData("EXEc CategoryTree")
Dim str As New StringBuilder
Dim catname As String = ""
Dim catid As Integer = 0
Dim parent As Integer = 0
Dim sort As String = ""
Dim keys As Array
Dim display As String = "none"
For Each item As DataRow In dt.Rows
catname = Replace(item("CatName"), " ", " ")
catid = item("id")
parent = item("parent")
sort = item("sort")
If parent = 0 Then
str.Append("<div class='group_" & parent & "'><a href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
Else
If Len(Me.GroupID) > 0 Then
keys = Split(Me.GroupID, "_")
For Each item1 As String In keys
If CInt(item1) = parent Then
str.Append("<div class='group_" & parent & "' style='display:block'><a style='text-decoration:none' href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
Else
'str.Append("<div class='group_" & parent & "' style='display:none'><a style='text-decoration:none' href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
End If
Next
End If
End If
Next
LMenu.Text = str.ToString
End Sub

Related

Get report parameters as URL string

I have an application that serves SSRS reports. A given report is accessed in the following way:
https://reportserver.com/reportname
Upon clicking View Report, a postback is submitted to the report server with the user-defined parameters. I need to grab these user-defined parameters and parse them as a URL string.
Desired result: https://reportserver.com/reportname?param1=foo&param2=bar
I found this doc that gets me close to what I need. This method should allow me to grab all visible parameters and parse them myself, but I need hidden parameters as well.
How can I build this parameter string? We're using JavaScript/jQuery in the front end so it may be possible to grab this client-side before the POST, but I haven't found a way of doing this either.
I got it working. Fair warning: I'm new to ASP.NET so this is likely not an ideal solution.
I added an event handler to the report viewer control's code behind. This queries the execution log, grabbing the parameters selected most recently by the user. It is meant to be triggered when a button called "Save Report" is clicked. If you try to handle this with a Load or PreRender event handler it will fire before the row has a chance to insert into the database, giving you the result of the user's second most recent execution parameters.
Define the Button (.ascx file)
<asp:LinkButton ID="SaveReportButton" runat="server" title="Save this Report"></asp:LinkButton>
Add event handler to code behind (.ascx.vb file)
Protected Sub SaveReportButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveReportButton.Click
Dim conn As New SqlConnection(<connection string here>)
Dim cmd As New SqlCommand("SELECT TOP 1 Parameters FROM [ReportServer].[dbo].[ExecutionLogStorage] WHERE <qualify on user, timestamp, etc. here>", conn)
cmd.Parameters.AddWithValue(<query parameter here>)
conn.Open()
Dim result = cmd.ExecuteScalar()
' Prevents NullReferenceException from result.ToString() in case no result is found
If (result IsNot Nothing)
' Redirect based on parameter string retrieved from log
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri & "?" & result.ToString())
End If
conn.Close()
End Sub
Call postback from JavaScript on button click
<li>
<a href=\'javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(<reference SaveReportButton with appropriate arguments>)\' id="SaveReportButton" title="Save Report">
Save Report
</a>
</li>
Documentation on WebForm_DoPostBackWithOptions() and WebForm_PostBackOptions() is sparse, but a colleague has already done it this way so I followed suit for consistency's sake because it works.
I've created URLs for reports with parameters 3 different ways. A combination of the the first two may get you closer to solving your problem.
Use custom code in the report properties.
Public Function ShowParameterValues(ByVal parameter As Parameter) As String
Dim s as String = String.Empty
Try
If parameter.IsMultiValue then
s = "Multivalue: "
For i as integer = 0 to parameter.Count-1
s = s + CStr(parameter.Value(i)) + " "
Next
Else
s = "Single value: " + CStr(parameter.Value)
End If
Return s
Catch ex As Exception
Return "error"
End Try
End Function
OR
Use a hyperlink in the report.
=Globals!ReportServerUrl + "/ReportServer?"
+ Replace(Globals!ReportFolder, " ", "+") + "%2f"
+ Replace(Globals!ReportName, " ", "+") + "&rs:Command=Render"
+ "&boolean_value=" + CStr(Parameters!boolean_value.Value)
+ "&single_value_parameter=" + Parameters!single_value_parameter.Value
+ "&multi_value_parameter=" + Join(Parameters!multi_value_parameter.Value, "&multi_value_parameter=")
+ IIf(IsNothing(Parameters!week_date_start.Value), "&week_date_start:isnull=True", "&week_date_start=" & Format(Parameters!week_date_start.Value, Variables!FormatDate.Value))
+ IIf(IsNothing(Parameters!week_date_end.Value), "&week_date_end:isnull=True", "&week_date_end=" & Format(Parameters!week_date_end.Value, Variables!FormatDate.Value))
Also, I usually add this as a report variable and then you can have a standard textbox for the footer that doesn't have to change.
=Variables!UrlReportWithParameters.Value
OR
Use the execution log. Check out the column URL_Report_Filtered
--Purpose: to search the reporting services execution log
DECLARE #all_value AS VARCHAR(10) = '<ALL>';
DECLARE #LogStatus AS VARCHAR(50) = '<ALL>';
DECLARE #ReportFolder AS VARCHAR(450) = 'Testing';
DECLARE #ReportName AS VARCHAR(450) = '<ALL>';
DECLARE #UserName AS VARCHAR(260) = '<ALL>';
DECLARE #GroupByColumn AS VARCHAR(50) = 'Report Folder';
DECLARE #StartDate AS DATETIME = NULL;
DECLARE #EndDate AS DATETIME = NULL;
WITH
report_users
AS
(
SELECT
[UserID]
, [UserName]
, [SimpleUserName] = UPPER(RIGHT([UserName], (LEN([UserName])-CHARINDEX('\',[UserName]))))
FROM
[dbo].[Users]
)
,
report_catalog
AS
(
SELECT
rpt.[ItemID]
, rpt.[CreatedById]
, rpt.[ModifiedById]
, rpt.[Type]
, rpt.[Name]
, [ReportName] = rpt.[Name]
, rpt.[Description]
, rpt.[Parameter]
, [CreationDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[CreationDate], 13))
, [ModifiedDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[ModifiedDate], 13))
, [ReportFolder] = SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2)
, rpt.[Path]
, [URL_ReportFolder] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2) + '&ViewMode=List'
, [URL_Report] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2) + '%2f' + rpt.[Name]
, [ReportDefinition] = CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), rpt.[Content]))
, [HostName] = Host_Name()
FROM
[dbo].[Catalog] AS rpt
WHERE
1=1
AND rpt.[Type] = 2
)
SELECT
[GroupBy1] =
CASE
WHEN #GroupByColumn = 'Report Name' THEN rpt.[ReportName]
WHEN #GroupByColumn = 'Report Folder' THEN rpt.[ReportFolder]
WHEN #GroupByColumn = 'User Id' THEN usr.[SimpleUserName]
ELSE '<N/A>'
END
, rpt.[Path]
, rpt.[ReportFolder]
, rpt.[Name]
, rpt.[URL_ReportFolder]
, rpt.[URL_Report]
, [URL_Report_Filtered] = rpt.[URL_Report] + '&rs:Command=Render&' + CONVERT(VARCHAR(max), el.[Parameters])
, [UserName] = usr.[SimpleUserName]
, el.[Status]
, el.[TimeStart]
, el.[RowCount]
, el.[ByteCount]
, el.[Format]
, el.[Parameters]
, [TotalSeconds] = CONVERT(CHAR(8),DATEADD(ms,(el.[TimeDataRetrieval] + el.[TimeProcessing] + el.[TimeRendering]),0),108)
, [TimeDataRetrieval] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeDataRetrieval],0),108)
, [TimeProcessing] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeProcessing],0),108)
, [TimeRendering] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeRendering],0),108)
, [OrderbyDate] = CAST([TimeStart] AS DATETIME)
FROM
report_catalog AS rpt
LEFT JOIN [dbo].[ExecutionLog] AS el ON el.[ReportID] = rpt.[ItemID]
LEFT JOIN report_users AS usr ON el.[UserName] = usr.[UserName]
WHERE
1=1
AND (#all_value IN(#LogStatus) OR el.[Status] IN(#LogStatus))
AND (#all_value IN (#ReportFolder) OR rpt.[ReportFolder] IN(#ReportFolder))
AND (#all_value IN(#ReportName) OR rpt.[ReportName] IN(#ReportName))
AND (#all_value IN(#UserName) OR usr.[SimpleUserName] IN(#UserName))
AND (#StartDate IS NULL OR CONVERT(DATETIME, CONVERT(VARCHAR(11), el.[TimeStart], 13)) >= #StartDate)
AND (#EndDate IS NULL OR CONVERT(DATETIME, CONVERT(VARCHAR(11), el.[TimeStart], 13)) <= #EndDate)

Dynamically updating dependent variables

Have just found a gaping hole in my cs knowledge... this code is written in VBA but I'd be really interested to know how to do this in javascript as well !
Basically I'm in a situation where a whole set of variables depends on one variable - something like this :
Sub test()
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
var1 = start + 1
var2 = start + 2
var3 = start + 3
End Sub
My problem is that I want the values of var1, var2 and var3 to update dynamically based on the value of start, for example
Sub test()
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
start = 0
var1 = start + 1
var2 = start + 2
var3 = start + 3
' would like to have var1 = 1, var2 = 2, var3 = 3
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
start = 5
' would now like to have var1 = 6, var2 = 7, var3 = 8
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
End Sub
But clearly this is not working, I get the same values
var1 = 1, var2 = 2, var3 = 3
both times. Is there a way to make this work in VBA ?
And is there a name for this kind of thing so I can better google it ? Something like "dynamic dependent variables" ? Many thanks !
I'm guessing that you are looking for something like Excel cell formulas and the way they cascade updates. There is no built-in mechanism for coding like that in VBA. There are some programming languages that use a paradigm called Functional Programming that behave in a similar way by chaining functions together and evaluating in a lazy manner, but VBA is more of a (weakly) object oriented, imperative flavor.
One way to solve this type of issue generally is by creating a class to encapsulate all your calculations and using member variables as the base elements of the calculations which would be set first, like start, and functions for the derivative numbers, like var1, var2, var3.
Here is an example. Create a class called clsRectangle and copy the following:
Option Compare Database
Option Explicit
Public length As Integer
Public width As Integer
Public Property Get diagonal() As Double
diagonal = VBA.Sqr((length ^ 2) + (width ^ 2))
End Property
Public Property Get area() As Integer
area = length * width
End Property
Public Property Get perimeter() As Integer
perimeter = 2 * (length + width)
End Property
Next create a module called mdlMain and add the following:
Public Sub Main()
Dim rect As clsRectangle
Set rect = New clsRectangle
With rect
.length = 3
.width = 5
MsgBox "perimeter: " & .perimeter & vbCrLf & _
"diagonal: " & .diagonal & vbCrLf & _
"area: " & .area & vbCrLf
'After changing the underlying numbers (like *start* in your example)
'area, perimeter and diagonal all return new values
.length = 2
.width = 7
MsgBox "perimeter: " & .perimeter & vbCrLf & _
"diagonal: " & .diagonal & vbCrLf & _
"area: " & .area & vbCrLf
End With
End Sub
Building a class at compile-time to handle formulaic calculations is good practice because it exposes your math and logic in a very maintainable way and benefits from the syntax and type-checking of the language. However, it does lack some of the flexibility of a run-time system. If you want to attempt something like that, I can give you some pointers, but it would be a pretty heavy lift to accomplish. I've done something similar in the past and had to implement [Topological Sort] to figure out what order to perform the calculation updates in based on a graph of prerequisites.
I can't speak to Javascript directly as I don't have too much experience with it. However, Javascript is a much more dynamic language than VBA and it's entirely possible that libraries already exist to do what you want.
as far as I'm aware this won't be possible in VBA. You could declare your variables at module level (outside of your procedure) and have them updating through a called function as outlined below. It's not quite as simple as you were perhaps expecting, but it is better than manually updating your variables every time 'start' changes.
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
Sub test()
start = 0
var1 = start + 1
var2 = start + 2
var3 = start + 3
' would like to have var1 = 1, var2 = 2, var3 = 3
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
start = ChangeStart(5)
' would now like to have var1 = 6, var2 = 7, var3 = 8
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
End Sub
Public Function ChangeStart(StartValue As Long)
start = StartValue
var1 = start + 1
var2 = start + 2
var3 = start + 3
End Function

How can I create a multi-level list menu from strings?

I am using vbscript inside an HTA to get a list of subnet locations and it returns text like the following:
Chicago
Denver
Dallas
Dallas/North
Dallas/South
Dallas/West
Dallas/West/Building1
Dallas/West/Building2
Houston
Sacramento/West
Sacramento/West/Building1
I'm trying to dynamically create an unordered list so that I can use jquery to create a collapsible menu.
I can cycle through an array, but building the nested <ul>s and <li>s are seemingly impossible. I have the jquery ready once the list is actually built, but I can't seem to build it.
Is there any jquery that can do this for me?
Where arrList is the list returned by the GetSubnetLocations function in the format above (alphabetized)
Dim arrMenu : ReDim arrMenu(-1)
Dim arrLocs : ReDim arrLocs(UBound(arrList),1)
i = 0
For Each x In arrList
'Also building option list here
intCount = Len(x) - Len(Replace(x,"/",""))
arrLocs(i,0) = x
arrLocs(i,1) = intCount
i = i + 1
Next
Result.InnerHTML = ""
ReDim Preserve arrMenu(UBound(arrMenu)+1)
arrMenu(UBound(arrMenu)) = "<ul id=""menu"">"
For x = 1 To UBound(arrLocs,1) Step 1
ReDim Preserve arrMenu(UBound(arrMenu)+1)
arrMenu(UBound(arrMenu)) = "<li><a>" & " " & arrLocs(x,0) & "</a></li>"
Next
For j = 1 To UBound(arrMenu)
If arrLocs(j,1) > arrLocs(j-1,1) Then
arrMenu(j-1) = Replace(arrMenu(j-1),"</li>","<ul style=""display:none"">")
End If
If arrLocs(j,1) < arrLocs(j-1,1) Then
For x = 1 To arrLocs(j-1,1) - arrLocs(j,1)
arrMenu(j-1) = arrMenu(j-1) & "</li>"
Next
End If
Next
ReDim Preserve arrMenu(UBound(arrMenu)+1)
arrMenu(UBound(arrMenu)) = "</ul>"
strMenu = ""
For Each n In arrMenu
strMenu = strMenu & n
Next
Result.InnerHTML = strMenu

Requesting field names and values from form and add them on the fly in a script

Hi I have a form and the action is submitting into a script named autoform.asp. In this script I usually request the fields values like this: txtFirstName = Request.Form("txtFirstname")
Now I want to make this to work dynamically without hard coding the requests in the script where the form is posting.
I managed to do this code to get the the form fields dynamically but they are not being loaded on the fly.
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(""& fieldName &" = Request.Form("""& fieldName &""")")
Next
The Response.Write is not good because it is stopping my script to continue. That said the values showing are correct. Can someone help me please? Maybe I need an array? and If yes how I can continue this process? THANKS
EDIT as per comment below
You can use the Execute statement to mimic import_request_variables from php
For Each Item In Request.Form
ItemValue = Request.Form(Item)
Execute Item & " = """ & ItemValue & """"
Next
If you are intending to output
Firstname = Request.Form("Firstname")
then use
<%
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(fieldName & " = Request.Form(""" & fieldName & """)")
Next
%>
If you are intending to output
Firstname = "John"
then use
<%
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(fieldName & " = """ & fieldValue & """")
Next
%>
I think you might be able to work something out using Execute(), eg
<%# language = "VBScript" CodePage = 65001 %>
<%
option explicit
dim q
for each q in Request.QueryString
dim s
s = "dim " & q & vbCrLf & _
q & " = """ & Request.QueryString(q) & """" & vbCrLf & _
"Response.Write ""Value of " & q & " is "" & " & q & vbCrLf
%>
<pre><%= s %></pre>
<hr/>
<%
Execute s
%><hr/><%
next
%>
(I've used the querystring collection so it's easier to test). So input like
http://.../test-asp.asp?p=1&c=328904
will generate something like
dim p
p = "1"
Response.Write "Value of p is " & p
Value of p is 1
dim c
c = "328904"
Response.Write "Value of c is " & c
Value of c is 328904
it depends on what you actually need to do.

javascript confirmation box? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Public Function CheckIfItemPresent(ByVal userID As String, ByVal itemID As String, ByVal itemPrice As Integer, ByVal offer As String) As Boolean
On Error GoTo galti
Dim sqlStatement As String = "SELECT itemQtty FROM shoppingCart WHERE userID = '" & _
userID & "' AND itemID = '" & itemID & "'" & _
" AND itemPrice = " & itemPrice & " AND offer = '" & offer & "'"
Dim con As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;" & _
"AttachDbFilename=|DataDirectory|\database.mdf;" & _
"Integrated Security=True;User Instance=True")
Dim sql As New SqlClient.SqlCommand(sqlStatement, con)
Dim reader As SqlClient.SqlDataReader
con.Open()
reader = sql.ExecuteReader
reader.Read()
Dim itemQtty As Integer = reader.Item("itemQtty")
reader.Close()
If itemQtty > 0 Then
If ***MsgBox("Item already present. Add another one? Currently, number of this item in cart: " & itemQtty, MsgBoxStyle.YesNo, "") = MsgBoxResult.Yes*** Then
itemQtty = itemQtty + 1
sql.CommandText = "UPDATE shoppingCart SET itemQtty = " & itemQtty & " WHERE " & _
"userID = '" & userID & "' AND itemID = '" & itemID & "' AND itemPrice=" & _
itemPrice & " AND offer = '" & offer & "'"
sql.ExecuteNonQuery()
Else
End If
End If
con.Close()
con.Dispose()
Return True
Exit Function
galti:
con.Close()
con.Dispose()
Return False
End Function
how to use javascript conformation box instead of asp.net msgbox...please check the portion in between *
There is no drop-in replacement to do that with Javascript.
To interact with the user you have to send a response back to the browser that it can display, then the user can make the choise and send another request to the server containing the information about the choise.
So, you have to divide this into two separate steps on the server side.
To make a confirmation box in Javascript you can use the confirm method. Example:
var choise = window.confirm('Item already present. Add another one? Currently, number of this item in cart: 42');

Categories

Resources