Microsoft Chart Control generates a different visual then the set property. Property based it always shows correct value but if you open the generated chart with graphic software like Photoshop it shows pixels are not matching with the set property.
I found this bug while trying to retrieve all InnerPlot Positions into a HiddenField. Based on this bug right now, there is no way to get correct absolute position of ChartAreas or InnerPlots. Please let me know if you believe there is a workaround about it...
Thank you for your time and attention...
STEPS TO REPRODUCE
Test.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %>
<%# Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Chart ID="Chart1" runat="server"></asp:Chart>
</div>
</form>
</body>
</html>
Test.aspx.vb
Imports System.Web.UI.DataVisualization.Charting
Partial Class Test
Inherits System.Web.UI.Page
Private Sub DataHelper()
Dim Historical() As String = _
{ _
"Date,Open,High,Low,Close,Volume", _
"2009-03-05,1.75,2.00,1.73,1.81,47339300", _
"2009-03-04,1.90,1.90,1.83,1.87,22306600", _
"2009-03-03,1.91,1.91,1.80,1.81,15412400", _
"2009-03-02,1.91,1.94,1.83,1.88,19585500", _
"2009-02-27,1.93,2.00,1.80,2.00,31469500", _
"2009-02-26,2.08,2.09,1.81,1.98,32307100", _
"2009-02-25,2.10,2.16,2.00,2.01,54325200", _
"2009-02-24,1.80,2.00,1.80,2.00,33935300", _
"2009-02-23,1.65,1.91,1.61,1.73,44444100", _
"2009-02-20,1.60,1.61,1.50,1.58,37889100" _
}
Dim Query As IEnumerable = From HistoricalLine In Historical Skip 1 _
Where Not String.IsNullOrEmpty(HistoricalLine) _
Let HistoricalFields = HistoricalLine.Split(",") _
Let HistoricalDate = CDate(HistoricalFields(0)) _
Order By HistoricalDate Ascending _
Select New With { _
.Date = HistoricalDate, _
.Open = CDbl(HistoricalFields(1)), _
.High = CDbl(HistoricalFields(2)), _
.Low = CDbl(HistoricalFields(3)), _
.Close = CDbl(HistoricalFields(4)), _
.Volume = CDbl(HistoricalFields(5)) _
}
Chart1.DataSource = Query
End Sub
Private Sub CreateChartArea(ByVal areaname As String)
Chart1.ChartAreas.Add(New ChartArea)
With Chart1.ChartAreas.Last
.Name = areaname
.AxisY2.Enabled = AxisEnabled.False
.AxisX2.Enabled = AxisEnabled.False
With .AxisX
.MajorTickMark.Enabled = False
.MinorTickMark.Enabled = False
.MinorGrid.Enabled = False
.MajorGrid.LineColor = Drawing.Color.Yellow
End With
With .AxisY
.MajorTickMark.Enabled = False
.MinorTickMark.Enabled = False
.MinorGrid.Enabled = False
.MajorGrid.LineColor = Drawing.Color.Red
.IsStartedFromZero = False
End With
.BackColor = Drawing.Color.SkyBlue
.BorderDashStyle = ChartDashStyle.Solid
.BorderColor = Drawing.Color.Brown
.BorderWidth = 0
.ShadowOffset = 0
End With
End Sub
Private Sub CreateSeries(ByVal seriename As String, ByVal areaname As String)
Chart1.Series.Add(New Series)
With Chart1.Series.Last
.Name = seriename
.ChartArea = areaname
.YValuesPerPoint = 4
.ChartType = SeriesChartType.Candlestick
.XValueType = ChartValueType.DateTime
.IsXValueIndexed = True
.XValueMember = "Date"
.YValueMembers = "High,Low,Open,Close"
.BorderColor = Drawing.Color.Green
.IsValueShownAsLabel = True
End With
End Sub
Private Sub ChartHelper()
Chart1.ImageStorageMode = ImageStorageMode.UseImageLocation
Chart1.ImageLocation = "~/_temp/HG_#SEQ(300,60)" '<= make sure you have "_temp" directory
Chart1.ImageType = ChartImageType.Png
Chart1.RenderType = RenderType.ImageTag
Chart1.Titles.Add(New Title())
Chart1.Legends.Add(New Legend())
Chart1.Legends.Last.Enabled = False
Chart1.Palette = ChartColorPalette.BrightPastel
Chart1.BackColor = Drawing.Color.Pink
CreateChartArea("A1")
CreateSeries("S1", "A1")
CreateChartArea("A2")
CreateSeries("S2", "A2")
CreateChartArea("A3")
CreateSeries("S3", "A3")
CreateChartArea("A4")
CreateSeries("S4", "A4")
Chart1.DataBind()
Chart1.SaveXml(Server.MapPath("~/_temp/MyChart.xml"))
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
DataHelper()
ChartHelper()
TestPart()
End If
End Sub
Private Sub TestPart()
Dim SpaceBetweenChartAreas As Single = 1 '<= %1 of Chart's Height
Chart1.Height = 500
Chart1.Width = 1000
Dim locator As Integer = 0
For Each chartareaItem In Chart1.ChartAreas
With chartareaItem
.Position.Auto = False
.Position.Height = 20 '500px/100*20 = 100px
.Position.Width = 80 '1000px/100*80 = 800px
.Position.X = 0
.Position.Y = locator
.InnerPlotPosition.Auto = False
.InnerPlotPosition.Height = 100 '%100 of ChartArea Position's Height
.InnerPlotPosition.Width = 100 ' %100 of ChartArea Position's Width
.InnerPlotPosition.X = 0
.InnerPlotPosition.Y = 0
locator += SpaceBetweenChartAreas + .Position.Height
End With
Next
End Sub
End Class
Please don't forget to create a directory "_temp"
Also you can see the actual result at http://ilerler.com/-bug4ms/Test.png
RESULTS
1st ChartArea Height
ACTUAL 101px | EXPECTED 100px
space
ACTUAL 4px | EXPECTED 5px
2nd ChartArea Height
ACTUAL 101px | EXPECTED 100px
space
ACTUAL 4px | EXPECTED 5px
3rd ChartArea Height
ACTUAL 100px | EXPECTED 100px
space
ACTUAL 4px | EXPECTED 5px
4th ChartArea Height
ACTUAL 101px | EXPECTED 100px
space
ACTUAL 85px | EXPECTED 85px
You have the following line:
Dim SpaceBetweenChartAreas As Single = 1 '<= %1 of Chart's Height
That means that your calculations are being performed with single precision float point values - which are highly susceptible to rounding errors.
At the very least you should use Double values.
Related
Right now, I'm developing web application using DevExpress BootstrapChart (v17.2.13.0) and I have binded the control with object datasource. Here is the example data used to be displayed in the graph:
Here is my objectives:
The graph will show the values of "ademand_im" and "rdemand_im" in different panes (I named them pane "A" and "B")
Each pane has "data_time" (date and time) as X-axis and the values ("ademand_im" or "rdemand_im") as Y-axis
Also, the values in each pane will be grouped by "hardware_id" so, in this case, there should be 2 line series of "83245551" and "88310991" in each pane (Note that "hardware_id" can be varied from time to time).
So the graph should look like this:
However, what I only acheive at this moment is that either the line series are shown in both panes but not grouped or not show anything in the graph.
Here is my code:
<dx:BootstrapChart ID="chart" ClientInstanceName="chart" runat="server"
DataSourceID="ods_ChartData" Height="640px" TitleText="Chart Data" CrosshairEnabled="true" Panes="A,B">
<ClientSideEvents Init="OnChartInit" />
<SettingsToolTip Shared="true" Enabled="true" OnClientCustomizeTooltip="ChartToolTip" />
<ArgumentAxis ArgumentType="System.DateTime" GridVisible="True" MinorGridVisible="True"
TickVisible="True" MinorTickVisible="True" TickInterval="1" MinorTickCount="3" TitleText="Date">
<Label DisplayMode="Rotate" RotationAngle="-0" Format-Formatter="FormatDate" />
</ArgumentAxis>
<ValueAxisCollection>
<dx:BootstrapChartValueAxis Pane="A" TitleText="ademand_im" />
<dx:BootstrapChartValueAxis Pane="B" TitleText="rdemand_im" />
</ValueAxisCollection>
<SettingsCommonSeries Type="Line" ArgumentField="data_time" Point-Size="0" />
<SettingsSeriesTemplate NameField="hardware_id" />
<SeriesCollection>
<dx:BootstrapChartLineSeries Pane="A" ValueField="ademand_im" />
<dx:BootstrapChartLineSeries Pane="B" ValueField="rdemand_im" />
</SeriesCollection>
</dx:BootstrapChart>
In this code, if I remove the "SettingsSeriesTemplate" line, the data will show in both panes but only in single line in each pane. However, if I keep this line the graph will not show anything.
After I tried to understand how this control works, the only solution I found is that I have to pivot "hardware_id" columns into "ademand_im" and "rdemand_im" values, which may be not the ideal one.
So instead of having "hardware_id", "ademand_im" and "rdemand_im" columns, the table should be transformed to have like "ademand_im_83245551", "ademand_im_88310991", "rdemand_im_83245551" and "rdemand_im_88310991" columns instead.
This is how the table after transforming looks like:
Here is the function codes that I used to transform the table (VB.NET):
<Extension()>
Public Function PivotDataTableColumnGroup(srcData As DataTable, rowGroupField As String, pivotColumnField As String, valueGroupFields As IEnumerable(Of String),
Optional ValueGroupColumnName As Func(Of String, String, String) = Nothing,
Optional otherFields As IEnumerable(Of String) = Nothing,
Optional GetOtherFieldValue As Func(Of DataTable, String, Object, Object) = Nothing
) As DataTable
Dim groupValueList As List(Of Object) = srcData.GetDistinctValuesByColumnName(rowGroupField)
Dim pivotValueList As List(Of Object) = srcData.GetDistinctValuesByColumnName(pivotColumnField)
Dim hasOtherFieldColumn As Boolean = Not (otherFields Is Nothing Or GetOtherFieldValue Is Nothing)
Dim dt As New DataTable
With dt
.Columns.Add(rowGroupField, srcData.Columns(rowGroupField).DataType)
For i As Integer = 0 To valueGroupFields.Count - 1
For j As Integer = 0 To pivotValueList.Count - 1
Dim columnName As String = GetColumnNameFromGroupFieldAndPivotValues(valueGroupFields(i), pivotValueList(j), ValueGroupColumnName)
dt.Columns.Add(columnName, srcData.Columns(valueGroupFields(i)).DataType)
Next
Next
If hasOtherFieldColumn Then
For i As Integer = 0 To otherFields.Count - 1
.Columns.Add(otherFields(i), srcData.Columns(otherFields(i)).DataType)
Next
End If
For i As Integer = 0 To groupValueList.Count - 1
Dim currentGroupValue As Object = groupValueList(i)
Dim dr As DataRow = dt.NewRow()
dr(rowGroupField) = currentGroupValue
If hasOtherFieldColumn Then
For j As Integer = 0 To otherFields.Count - 1
dr(otherFields(j)) = DBNullIfNothing(GetOtherFieldValue(srcData, otherFields(j), currentGroupValue))
Next
End If
For j As Integer = 0 To valueGroupFields.Count - 1
Dim currentField As String = valueGroupFields(j)
For k As Integer = 0 To pivotValueList.Count - 1
Dim currentPivotValue As Object = pivotValueList(k)
Dim columnName As String = GetColumnNameFromGroupFieldAndPivotValues(valueGroupFields(j), pivotValueList(k), ValueGroupColumnName)
Dim value As Object = (From row In srcData.AsEnumerable
Where row(rowGroupField) = currentGroupValue _
AndAlso row(pivotColumnField) = currentPivotValue
Select row(currentField)
).FirstOrDefault
dr(columnName) = DBNullIfNothing(value)
Next
Next
dt.Rows.Add(dr)
Next
End With
Return dt
End Function
<Extension()>
Public Function GetDistinctValuesByColumnName(dt As DataTable, columnName As String) As List(Of Object)
Dim valueList As List(Of Object) = (From row As DataRow In dt.AsEnumerable
Where Not IsDBNull(row(columnName))
Order By row(columnName)
Select row(columnName) Distinct
).ToList
Return valueList
End Function
Private Function GetColumnNameFromGroupFieldAndPivotValues(groupField As String, pivotValue As Object, Optional ValueGroupColumnName As Func(Of String, String, String) = Nothing) As String
Dim columnName As String = groupField & "_" & pivotValue.ToString()
If ValueGroupColumnName IsNot Nothing Then
columnName = ValueGroupColumnName(groupField, pivotValue)
End If
Return columnName
End Function
Public Function DBNullIfNothing(o As Object) As Object
If o Is Nothing Then Return DBNull.Value
Return o
End Function
And this is how I used the function to transform the table:
Dim chartData As DataTable = result.PivotDataTableColumnGroup("data_time", "hardware_id", {"ademand_im", "rdemand_im"}, Nothing, Nothing, Nothing)
ResultChartData = chartData 'Stored in ASPxHiddenField in JSON form
After that, instead of setting chart series properties in aspx file, I have to add chart series manually in code behind:
Private Sub chart_LoadProfile_DataBound(sender As Object, e As EventArgs) Handles chart_LoadProfile.DataBound
Using ResultChartData
Dim seriesList As List(Of String) = (From col As DataColumn In ResultChartData.Columns
Where col.ColumnName <> "data_time"
Order By col.ColumnName
Select col.ColumnName
).ToList
Dim hardWardCount As Integer = (From s In seriesList Where s.Contains("ademand_im_")).Count
Dim showInLegend As Boolean = hardWardCount > 1
With chart_LoadProfile.SeriesCollection
.Clear()
For i As Integer = 0 To seriesList.Count - 1
Dim fieldName As String = seriesList(i)
Dim hardwareId As String = seriesList(i).Split("_")(2)
Dim series As New BootstrapChartLineSeries
With series
.ArgumentField = "data_time"
.ValueField = fieldName
.Point.Size = 0
.ShowInLegend = showInLegend
If fieldName.Contains("ademand_im_") Then
.Pane = "A"
.Name = "kW - " & hardwareId
Else
.Pane = "B"
.Name = "kVar - " & hardwareId
End If
End With
.Add(series)
Next
End With
End Using
End Sub
I am trying to make this function return a (list/multidarray) of the 7 BranchHours.childnodes for this branchID that I can call with a little code in my codebehind page.
here is what one section of the xmlfile looks like (BranchesInfo)
<BranchInfo>
<BranchId>db</BranchId>
<Name></Name>
<ShortName></ShortName>
<ImageUrl></ImageUrl>
<BranchHours>
<Hours>
<DayOfWeek>Sunday</DayOfWeek>
<Open>12:00</Open>
<Close>5:00</Close>
</Hours>
<Hours>
<DayOfWeek>Monday</DayOfWeek>
<Open>10:00</Open>
<Close>8:00</Close>
</Hours>
<Hours>
<DayOfWeek>Tuesday</DayOfWeek>
<Open>10:00</Open>
<Close>8:00</Close>
</Hours>
<Hours>
<DayOfWeek>Wednesday</DayOfWeek>
<Open>10:00</Open>
<Close>8:00</Close>
</Hours>
<Hours>
<DayOfWeek>Thursday</DayOfWeek>
<Open>10:00</Open>
<Close>6:00</Close>
</Hours>
<Hours>
<DayOfWeek>Friday</DayOfWeek>
<Open>10:00</Open>
<Close>6:00</Close>
</Hours>
<Hours>
<DayOfWeek>Saturday</DayOfWeek>
<Open>12:00</Open>
<Close>5:00</Close>
</Hours>
</BranchHours>
</BranchInfo>
code
'app_code function below
Public Shared Function MyFunc(ByVal branchCode As String) As List(Of String)
Dim URLString As String = "url/branchesTesting.xml"
Dim xmlDoc As XDocument = XDocument.Parse(URLString)
XDocument.Load(URLString)
Dim labelMan As List(Of String)
Dim x As Integer = (0) 'looping variable
' Dim i As Integer = 1
Dim branchid = xmlDoc.XPathSelectElements("/BranchesInfo/BranchInfo[BranchId='" & branchCode & "']/BranchHours/Hours")
'Dim varList As New List(Of String)
Dim Items = From BranchHours In xmlDoc.XPathSelectElements("/BranchesInfo/BranchInfo[BranchId='" & branchCode & "']/BranchHours/Hours") _
Select DayOfWeek = (BranchHours.Elements("DayOfWeek").Value),
Open = (BranchHours.Elements("Open").Value), _
Close = (BranchHours.Elements("Close").Value)
' Dim lists = xmlDoc.Root.Elements("BranchHours").[Select](Function(element) element.Value).ToList()
For Each Hours In Items
' For i As Integer = 0 To Items.Count - 1
' lists = labelMan
labelMan = "<div>DayOfWeek:" & Hours.DayOfWeek & "Open:" & Hours.Open & "Close: " & Hours.Close & "</div>" ' ----- error Error 34 Value of type 'String' cannot be converted to 'System.Collections.Generic.List(Of String)'.
' Else
' i += 1
' End If
labelMan = labelMan
'Next
Next
' If labelMan = "" Then
'labelMan = "No Results."
'End If
Return labelMan
End Fuction
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Call BranchHours.branchHours.MyFunc("dr")
Label1.Text = BranchHours.branchHours.MyFunc("dr") ' ----- Error Error 35 Value of type 'System.Collections.Generic.List(Of String)' cannot be converted to 'String'.
End Sub
Ideal Results
Day of the Week Open Close
(0)Sunday 12:00 5:00
(1)Monday 10:00 8:00
(2)Tuesday 10:00 8:00
(3)Wednesday 10:00 8:00
(4)Thursday 10:00 6:00
(5)Friday 10:00 6:00
(6)Saturday 10:00 5:00
--- the (i) would not be visible its for referencing the results in the future.
please let me know if you need any additional information. Thank you!
First you need to instantiate your List(of String). Right now for you it is Nothing.
Dim labelMan As List(Of String) = New List(of String)
Then you need to use the List(of T) Add method:
labelMan.Add("<div>DayOfWeek:" & Hours.DayOfWeek & "Open:" & Hours.Open & "Close: " & Hours.Close & "</div>")
Thanks Again to those who helped me. Here the complete answer w/ comments:)
side note -- This code will be audited, so for those who can see places that I should add testing or should make improvement in the code below. Please feel free to advise/comment.
App_Code Function >
Namespace BranchHours
Public Class branchHours
'function will accecpt string of branch ID and return value to be a List(of string)
Public Shared Function MyFunc(ByVal branchCode As String) As List(Of String)
'set XML URL path
Dim URLString As String = "url/branchesTesting.xml"
'load URL Path
Dim xmlDoc As XDocument = XDocument.Load(URLString)
' instantiate List(of String)
Dim labelMan As List(Of String) = New List(Of String)
'define items start path in xml document based on passsed branchcode id
'select and set xml element variable and return value/innertext for branch hours
Dim Items = From BranchHours In xmlDoc.XPathSelectElements("/BranchesInfo/BranchInfo[BranchId='" & branchCode & "']/BranchHours/Hours") _
Select DayOfWeek = (BranchHours.Elements("DayOfWeek").Value),
Open = (BranchHours.Elements("Open").Value), _
Close = (BranchHours.Elements("Close").Value) _
'BranchID = (branchname.Elements("BranchId").Value)
For Each Hours In Items
' use the List(of T) Add method: to add each hours' nodes to list, you can also add some html tags here if you to style it a bit more then plain text
labelMan.Add(Hours.DayOfWeek & "," & Hours.Open & "," & Hours.Close)
Next
Return labelMan
End Function
End Class
End Namespace
Code Behind >
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' this line will call one of the specified list items
Label2.Text = BranchHours.branchHours.MyFunc("dr").ElementAt(1)
Call BranchHours.branchHours.MyFunc("dr")
'This block below will return the full list of branchhours
Dim i As Integer = 0
Dim rangex As List(Of String) = BranchHours.branchHours.MyFunc("dr")
Dim message = String.Join(Environment.NewLine, rangex.ToList())
For Each Items As String In rangex
' Do something with items
Label1.Text = message
'Next
End Sub
Front .aspx
<%# Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="Default3bh.aspx.vb" Inherits="Default3bh" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Label ID="Label1" runat="server" ></asp:Label>
<asp:Label ID="Label2" runat="server" ></asp:Label>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="AdditionalContent" Runat="Server">
</asp:Content>
Results >
Label2 : Monday,10:00,6:00
label1 : Sunday,Closed,Closed Monday,10:00,6:00 Tuesday,10:00,8:00 Wednesday,10:00,6:00 Thursday,10:00,6:00 Friday,10:00,6:00 Saturday,10:00,5:00
Below are the aspx and vb code file for the problem page. The problem page works when only one user is logged in and viewing. Although, when another user logs in and views the same page then this happens ard(i) <> xxz(i)
Then Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End If
And the page reloads repetitively. So, ard(i) <> xxz(i) happens when multiple users are logged in viewing. How can one user be affected by another user viewing and making selections on the same page? Everything is fine with one user not when multiple users are playing around on this page.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="vwall_tour.aspx.vb" Inherits="vwall_tour2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="../js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="../flowplayer/flowplayer-3.2.4.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="../flowplayer/flowplayer-3.2.4.min.js"> </script>
<script type="text/javascript">
function OpenTourManager() {
document.location.href = 'manage_tours.aspx';
//document.location.href = 'manage_tours.aspx?tourid=' +
document.getElementById('ddlAvailableTours').options[document.getElementById('dd lAvailableTours').selectedIndex].value;
}
</script>
</head>
<body>
<form id="form1" style="height:100%; vertical-align:middle" runat="server">
<table border=0 cellpadding=0 cellspacing=0 width=100% background="../images/gray.jpg">
<tr>
<td><img src="../images/cyberco-banner.gif" height="35px" alt="CYBERCO" /></td>
<td><asp:Button runat="server" ID="btnSignOut" Text = "Sign Out" /></td>
<td><input type = "button" value ="Change Password" onclick="javascript: document.location.href = '../changepassword.aspx';" id="btnChangePass"/></td>
<td></td>
<td><asp:Label ID ="lblUsername" runat="server"> </asp:Label></td>
<td width="400px"> </td>
<td><asp:DropDownList ID = "ddlAvailableTours" runat="server" Width="250px" OnSelectedIndexChanged="SelectionChanged" AutoPostBack="True"></asp:DropDownList></td>
<td><asp:Button runat="server" id="btnSetDefaultTour" Text="Set as default" /></td>
<td><input type='button' value='Manage Video Wall' onclick="javascript: OpenTourManager(); "/></td>
<td><input type="hidden" id ="startstop" onclick= "javascript: vwallStartStop();" /></td><td>(Fullscreen-> F11)<!--<input type="button" value="Fullscreen mode" onclick=" toggleFull()" />--></td>
</tr>
</table>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" /><asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="5000" /><table border=0 cellspacing=0 cellpadding=0 id="main" style="height:100%; width:100%; padding:0px; margin:0px; background-color:#000000;">
<tr><td align=right style="vertical-align:top; border:0px; padding:0px;" align=top padding=0 valign=top class='header_row' id="tdheader">
<div id="header" class="style1">
<div id = "clockid" style="visibility:hidden; border:0px; padding:0px;" > clock</div>
<!---<table border=2 cellpadding=0 cellspacing=0 padding=0 style="text-align:center;height:564;width:100%;padding:0;margin:0;" bgcolor=#425081 >-->
<tr>
<td padding=0 width=0px" width=0%>
<asp:UpdatePanel ID="up_setdefault" UpdateMode="Conditional" runat="server" RenderMode="Inline">
<Triggers><asp:AsyncPostBackTrigger ControlID="Timer1" /></Triggers>
<ContentTemplate>
<asp:Label id="StockPrice" runat="server"></asp:Label>
<fieldset style="border:0; margin=0px; cellpadding=0; padding=0px; cellspacing=0; align=right; width=0px;" width=0%>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<!--</table>-->
<tr><td padding=0 style="border:0px; padding:0px;"> <asp:Literal runat="server" ID="litTableInner1"></asp:Literal></td></tr></table>
<!-- cut script -->
<asp:Literal runat="server" ID="litCreatePlayersScript"></asp:Literal>
<asp:Literal runat="server" ID="litCreateUpdateScript"></asp:Literal>
</form>
</body>
</html>
Then the vb code file...
Imports System.Data.SqlClient
Imports System.Data
Imports System.Net
Public Class vwall_tour2
Inherits System.Web.UI.Page
Public Shared xxz(9) As String
'Protected default_wstr As String = ConfigurationManager.AppSettings("default_wstr")
'Dim xxz = {"Off", "Off", "Off", "Off", "Off", "Off", "Off", "Off", "Off"}
Protected Sub vwall_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
Me.lblUsername.Text = User.Identity.Name
Dim auto_refresh_users As String()
auto_refresh_users = Split(ConfigurationManager.AppSettings("wall_logins_noexpire").ToString, ",")
Dim lausername As String
For Each lausername In auto_refresh_users
If Trim(lausername) = User.Identity.Name Then
Dim s As New StringBuilder
s.AppendLine("setTimeout ( 'reloadit();', reloadtime ); ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "loadAfterSigninFromVwall", s.ToString(), True)
Exit For
End If
Next
' if not found, will time out after 2 hrs and have to log in again
Dim selected_tour_id As Integer
If Not Page.IsPostBack Then
'btnAdmin.Visible = False
Dim ds As DataSet
ds = dataFetcher.fillDataset("User_SelectTours " & thisUser.userid, ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
ddlAvailableTours.DataSource = ds
ddlAvailableTours.DataValueField = "tour_id"
ddlAvailableTours.DataTextField = "tour_name"
ddlAvailableTours.DataBind()
If Not Request.QueryString("tour_id") Is Nothing Then
Try
selected_tour_id = Convert.ToInt16(Request.QueryString("tour_id"))
Catch ex As Exception
selected_tour_id = ddlAvailableTours.Items(0).Value
End Try
ElseIf thisUser.default_tour_id <> -1 Then
selected_tour_id = thisUser.default_tour_id
Else
selected_tour_id = ddlAvailableTours.Items(0).Value
End If
Dim itemfound As Boolean = False
Dim item As ListItem
For Each item In ddlAvailableTours.Items
If item.Value = selected_tour_id Then
item.Selected = True
itemfound = True
Exit For
End If
Next
If Not itemfound Then 'default or querystring tour_id not found
ddlAvailableTours.SelectedIndex = -1
ddlAvailableTours.Items(0).Selected = True
End If
Me.ddlAvailableTours_SelectedIndexChanged(Nothing, Nothing)
End If ' notpostback
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
StockPrice.Text = DateTime.Now.ToLongTimeString()
'TimeOfPrice.Text = DateTime.Now.ToLongTimeString()
End Sub
Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
''load the page
Dim selected_tour_id As Integer
selected_tour_id = ddlAvailableTours.SelectedValue
Dim t As user_Tour
For Each t In thisUser.user_Tours
If t.tour_id = selected_tour_id Then
StockPrice.Text = GetOverrideStatus(t)
Exit For
End If
Next
''''''
End If
End Sub
Function GetOverrideStatus(ByVal tour As user_Tour) As String
On Error Resume Next
Dim rstrf As New StringBuilder
'create the playlist string
Dim playlists As String()
Dim phaseitems As String()
Dim numPlayers As Integer = tour.num_cols * tour.num_rows
ReDim playlists(numPlayers - 1)
Dim dsd As DataSet
Dim stream_address As String
Dim VideoLabel As Object
Dim ard(9) As String
'ard = {"Off", "Off", "Off", "Off"}
Array.Clear(ard, 0, ard.Length)
For Each p In tour.phases
phaseitems = p.str_all_items.Split(",")
For i = 0 To numPlayers - 1
Dim s_id As String = phaseitems(i)
If p.tour_phase_id > 1 Then
playlists(i) &= ", "
End If
If Not s_id = "empty" And Not s_id = "" Then
dsd = dataFetcher.fillDataset("ListImageAllFields '" & s_id & "'", ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
ard(i) = dsd.Tables(0).Rows(0).Item("active_override")
' rstrf.AppendLine("A" + ard(i))
' rstr.AppendLine(ard(i))
If ard(i) <> xxz(i) Then
'Response.Write("<script>window.opener.location.href = window.opener.location.href </script>")
Response.Redirect("/media_dev/vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End If
' If ds.Tables(0).Rows(0).Item("active_override") = "On" Then
'Response.Redirect("../default.aspx")
' End If
'playlists(i) &= "'" & stream_address & "'"
Else ' empty spot
'playlists(i) &= "'../images/tours/tour_empty_space.png'"
End If 's not blank
Next
Next
'If ard(0) <> xxz(0) Or ard(1) <> xxz(1) Or ard(2) <> xxz(2) Or ard(3) <> xxz(3) Then
'Response.Write("<script>window.opener.location.href = window.opener.location.href </script>")
'Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
' End If
'Return ard.ToString("C")
Return ard(0).ToString() + ard(1).ToString() + ard(2).ToString() + ard(3).ToString() + ard(4).ToString() + ard(5).ToString() + ard(6).ToString() + ard(7).ToString() + ard(8).ToString()
End Function
Sub writeTableString(ByVal tour As user_Tour)
Dim returnstr As New StringBuilder
Dim td_width, td_height As Integer
td_width = Math.Floor(100 / tour.num_cols)
td_height = Math.Floor(100 / tour.num_rows) 'was 90
Dim rstr As New StringBuilder
Dim countinner, countouter As Integer
countinner = 0
countouter = 0
Do
rstr.AppendLine("<tr>")
Do
rstr.AppendLine("<td style='width:" & td_width & "%; height:" & td_height & "%;'><a runat='server' id='player" & (countinner + (countouter * tour.num_cols)) & "' href='#'></a></td>")
countinner += 1
Loop Until countinner = tour.num_cols
rstr.AppendLine("</tr>")
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
rstr.AppendLine("<script> document.getElementById('tdheader').colSpan='" & tour.num_cols & "';</script>")
Me.litTableInner1.Text = rstr.ToString
End Sub
Sub writeScriptForPlayers(ByVal tour As user_Tour)
On Error Resume Next
Dim rstr As New StringBuilder
'create the playlist string
Dim playlists As String()
Dim phaseitems As String()
Dim numPlayers As Integer = tour.num_cols * tour.num_rows
ReDim playlists(numPlayers - 1)
Dim ds As DataSet
Dim stream_address As String
Dim VideoLabel As Object
Array.Clear(xxz, 0, xxz.Length)
For Each p In tour.phases
phaseitems = p.str_all_items.Split(",")
For i = 0 To numPlayers - 1
Dim s_id As String = phaseitems(i)
If p.tour_phase_id > 1 Then
playlists(i) &= ", "
End If
If Not s_id = "empty" And Not s_id = "" Then
ds = dataFetcher.fillDataset("ListImageAllFields '" & s_id & "'", ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
xxz(i) = ds.Tables(0).Rows(0).Item("active_override")
rstr.AppendLine("B" + xxz(i))
If ds.Tables(0).Rows(0).Item("active_override") = "Off" Then
If ds.Tables(0).Rows(0).Item("hq_viewcapable") = "Y" Then
If ds.Tables(0).Rows(0).Item("hq_firstresponder") = "Y" Then
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP_hq").ToString()
Else
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP").ToString()
End If
Else
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP").ToString()
End If
Else : stream_address = "../overridden.swf"
End If
playlists(i) &= "'" & stream_address & "'"
' Else ' empty spot
'playlists(i) &= "'../images/tours/tour_empty_space.png'"
End If 's not blank
Next
Next
' end creating playlist strings
Dim countinner, countouter As Integer
countinner = 0
countouter = 0
rstr.AppendLine("<script type='text/javascript'>")
Do
Do
countinner += 1
Loop Until countinner = tour.num_cols
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
''write the players
countinner = 0
countouter = 0
Do
Do
rstr.AppendLine("flowplayer('player" & (countinner + (countouter * tour.num_cols)) & "', '../flowplayer/flowplayer.commercial-3.2.5.swf', { key: '#$34tg5y5y5hytr', logo: { url:'../images/CYBERLOGO.PNG', opacity: 0.65, top: 10, right: 10, fullscreenOnly: false }, playlist: [" & playlists(countinner + (countouter * tour.num_cols)) & "], clip: { provider: 'CYBERCO', live: true, onBegin: function () { clearTimer(); }, onBeforeFinish: function () { this.getPlugin('play').hide(); return false; } }, onLoad: function () { setTimer(); }, onPlaylistReplace: function () { setTimer(); }, onError: function () { error(); }, play:{ opacity:0.0, label:null, replayLabel: null }, onFinish: function(){ this.play(); }, plugins: { CYBERCO: { url: '../flowplayer/flowplayer.rtmp-3.2.3.swf', live: true, controls: { autoHide: true}}} })")
'logo: { url:'/first_resp/images/cyberco-banner.gif', opacity: 0.4, bottom: 20, right: 20 },
' rstr.AppendLine("flowplayer('player" & (countinner + (countouter * tour.num_cols)) & "', '../flowplayer/flowplayer.commercial-3.2.5.swf', { key: '#$34tg5y5y5hytr', logo: { url:'..images/CYBERLOGO.PNG', opacity: 0.65, top: 10, right: 10, fullscreenOnly: false }, playlist: [" & playlists(countinner + (countouter * tour.num_cols)) & "], clip: { provider: 'CYBERCO', live: true, onBegin: function () { clearTimer(); }, onBeforeFinish: function () { this.getPlugin('play').hide(); } }, onLoad: function () { setTimer(); }, onPlaylistReplace: function () { setTimer(); }, onError: function () { error(); }, plugins: { CYBERCO: { url: '../flowplayer/flowplayer.rtmp-3.2.3.swf', live: true, controls: { autoHide: true}}} })")
countinner += 1
Loop Until countinner = tour.num_cols
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
rstr.AppendLine("</script>")
Me.litCreatePlayersScript.Text = rstr.ToString
End Sub
Public Function loadWallData(ByVal wstr As String) As DataSet
Try
'If Me.loggedin Then
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString)
Dim dsStreams As New DataSet
'add the quotes to the strings
wstr = wstr.Replace(",", "','")
wstr = "'" & wstr & "'"
Dim sqltext As String = "[User_SelectVWallStreams] " & wstr
Dim da As New SqlDataAdapter
Dim Command As New SqlCommand
Command = New SqlCommand(sqltext, conn)
'Command.CommandType = CommandType.StoredProcedure
da.SelectCommand = Command
da.Fill(dsStreams)
Return dsStreams
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Protected Sub SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End Sub
Protected Sub ddlAvailableTours_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlAvailableTours.SelectedIndexChanged
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
''load the page
Dim selected_tour_id As Integer
selected_tour_id = ddlAvailableTours.SelectedValue
If selected_tour_id = thisUser.default_tour_id Then
Me.btnSetDefaultTour.Enabled = False
Else
Me.btnSetDefaultTour.Enabled = True
End If
Dim t As user_Tour
For Each t In thisUser.user_Tours
If t.tour_id = selected_tour_id Then
'selected_tour_id = ddlAvailableTours.SelectedValue
writeTableString(t)
writeScriptForPlayers(t)
' Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & selected_tour_id)
Exit For
End If
Next
End If
End Sub
Protected Sub btnSetDefaultTour_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSetDefaultTour.Click
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
thisUser.UpdateDefaultTour(Me.ddlAvailableTours.SelectedValue)
Me.btnSetDefaultTour.Enabled = False
End If
End Sub
Protected Sub btnSignOut_Click(sender As Object, e As System.EventArgs) Handles btnSignOut.Click
FormsAuthentication.SignOut()
'delete the cookie (or will be infinite loop)
'delete the cookie
Dim aCookie As HttpCookie
If Request.Cookies("cyber_Load") Is Nothing Then
'Response.Cookies.Add(aCookie)
Response.Redirect("../default.aspx")
Else
aCookie = Request.Cookies("cyber_Load")
aCookie.Expires = DateTime.Now.AddDays(-1D)
Response.Cookies.Add(aCookie)
Response.Redirect("../default.aspx")
End If
End Sub
End Class
The reason for that is:
Public Shared xxz(9) As String
By declaring the variable as Shared, there only ever exists one instance of the variable, shared by all users. Whatever one user puts in the variable is visible to all other users.
You would rather store the array in the Session collection, so that each user can have one array of their own.
Declare the array variable as an instance variable, so that it's local to the current page, and don't create the actual array yet:
Public xxz As String()
In the beginning of the code, get the array from the Session collection, or create a new one if there is no array since before:
xxz = DirectCast(Session("xxz"), String())
If xxz Is Nothing Then
ReDim xxz(9)
Session("xxz") = xxz
End If
I have a repeater list that displays results in sets of 15. When you click the next button it shows the next 15 and so on.
I have added some buttons that will then filter the display to show the results in sets of 10, 25, 50.
When you click these it does work but when you click the next button it resets the display value to 15.
Below is the chunk of script:
Public Property CurrentPage() As Integer
Get
' look for current page in ViewState
Dim o As Object = Me.ViewState("_CurrentPage")
If o Is Nothing Then
Return 0
Else
' default to showing the first page
Return CInt(o)
End If
End Get
Set
Me.ViewState("_CurrentPage") = value
End Set
End Property
Protected Sub ItemsGet()
Dim pageSize As Integer = 15
ItemsGet(pageSize)
End Sub
Private Sub ItemsGet(ByVal pageSize As Integer)
' Read sample item info from XML document into a DataSet
' Populate the repeater control with the Items DataSet
Dim objPds As New PagedDataSource()
Dim selectedCategory As String = ddlCategory.SelectedValue.ToString()
Dim selectedCategoryIndex As Integer = ddlCategory.SelectedIndex
Dim selectedCategoryMonth As String = ddlCategoryMonth.SelectedValue.ToString()
Dim selectedCategoryMonthIndex As Integer = ddlCategoryMonth.SelectedIndex
Dim query = GetXmlDataSet()
If (Not String.IsNullOrEmpty(selectedCategory) And selectedCategoryIndex > 0) Then
query = query.Where(Function(x) x("SCategoryName") = selectedCategory)
End If
If (Not String.IsNullOrEmpty(selectedCategoryMonth) And selectedCategoryMonthIndex > 0) Then
query = query.Where(Function(x) x("SCategoryMonth") = selectedCategoryMonth)
End If
If (query.Count() > 0) Then
objPds.DataSource = query.CopyToDataTable().Rows
objPds.AllowPaging = True
objPds.PageSize = pageSize
objPds.CurrentPageIndex = CurrentPage
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString()
' Disable Prev or Next buttons if necessary
cmdPrev.Enabled = Not objPds.IsFirstPage
cmdNext.Enabled = Not objPds.IsLastPage
Display10.Enabled = True
Display25.Enabled = True
Display50.Enabled = True
categories.DataSource = objPds
categories.DataBind()
Else
CurrentPage = 0
categories.Controls.Clear()
cmdPrev.Enabled = False
cmdNext.Enabled = False
Display10.Enabled = False
Display25.Enabled = False
Display50.Enabled = False
lblCurrentPage.Text = "Page: 0 of 0 "
End If
End Sub
Private Sub Display10_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 10
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display25_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 25
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display50_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 50
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub cmdPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the previous page
CurrentPage -= 1
' Reload control
ItemsGet()
End Sub
Private Sub cmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the next page
CurrentPage += 1
' Reload control
ItemsGet()
End Sub
Protected Sub ddlCategory_SelectedIndexChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
Protected Sub ddlCategoryMonth_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
You need to 'persist' the number of items to get.
There are a few ways to do this....
Re-factor PageSize into a property with its backing kept in the viewstate, remember to initialise with appropriate default values.
Change the ItemsGet sub to use the property instead.
My vb is rusty!
Public Property PageSize() As Integer
Get
If Me.ViewState("PageSize") Is Nothing Then
Me.ViewState("PageSize") = 15
End If
Return CInt( Me.ViewState("PageSize") )
End Get
Set
Me.ViewState("PageSize") = value
End Set
End Property
I have a GridView which is showing results and from which I am deleting a result using the auto-created delete link. My code behind to remove the row and associated info. is:
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
' The deletion of the individual row is automatically handled by the GridView.
Dim dbDelete As New pbu_housingEntities
' Remove individual from the bed.
Dim remove_bed = From p In dbDelete.Beds _
Where p.occupant = GridView1.SelectedRow.Cells(3).Text _
Where p.room = GridView1.SelectedRow.Cells(6).Text _
Where p.building = GridView1.SelectedRow.Cells(5).Text _
Order By p.id Descending _
Select p
remove_bed.First.occupant = ""
dbDelete.SaveChanges()
' Increase number of open spaces in room.
Dim update_occupancy = From p In dbDelete.Rooms _
Where p.room1 = GridView1.SelectedRow.Cells(6).Text
Where p.building = GridView1.SelectedRow.Cells(5).Text _
Select p
update_occupancy.First.current_occupancy = update_occupancy.First.current_occupancy - 1
dbDelete.SaveChanges()
End Sub
It seems that it is not able to grab the row that is being deleted, so it is always giving me a "Object reference not set to an instance of an object" error.
Use GridView1.Rows(e.RowIndex).Cells(.......