Loop through XML elements in XmlDataSource in code behind - xpath

I have an XmlDataSource and a GridView on my page. On the Page_Load event, I apply an XPath to filter the xml elements according to the input of the user, LexiqueXmlDataSource.XPath = 'Some_XPath_here'; and it works just ok.
What I want is to access the elements that the XmlDataSource returns from codebehind after applying the XPath expression (and hence get their number).
I tried the GetXmlDocument() method but it returns the whole original Xml file rather than the filtered elements with XPath.
EDIT:
here is some code and the scenario I want:
protected void Page_Load(object sender, EventArgs e)
{
string xpath = "/lexique/item[starts-with(#acronym, '" + filter + "')]";
LexiqueXmlDataSource.XPath = xpath;
// Here the XmlDataSource have filtered the xml elements to return to the GridView
//I want to know how many element passed this filter using the XmlDataSource itself
}
Thank you.

Here is what I could come up with.
For the number of hits. Use the GridView row count. Indeed the GetXmlDocument.ChildNodes.Count always return the number of lexical items, not the number of hits whan the XPath expression is applied.
Test XML
<?xml version="1.0" encoding="utf-8" ?>
<lexique>
<item acronym="WPF" value="Windows Presentation Foundation"/>
<item acronym="SO" value="StackOverflow"/>
</lexique>
Minimalist ASP.net Page
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="xmlgrid.aspx.vb" Inherits="WebApplication1.WebForm1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="FilterLabel" runat="server" Text="Acronym starting with:"></asp:Label>
<asp:TextBox ID="FilterTextBox" runat="server"></asp:TextBox>
<asp:XmlDataSource ID="LexiqueXmlDataSource" runat="server" DataFile="~/lexique.xml">
</asp:XmlDataSource>
<asp:GridView ID="LexiqueGrid" runat="server" AllowSorting="true" BorderStyle="Groove">
<Columns>
<asp:TemplateField HeaderText="Acronym">
<ItemTemplate>
<%# XPath("/lexique/item/#acronym")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# XPath("/lexique/item/#value")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Hits" runat="server" Text="Acronyms found"></asp:Label>
<asp:Button ID="Submit" runat="server" Text="Search" />
</div>
</form>
</body>
</html>
Code Behind
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim XPath As String
If String.IsNullOrEmpty(FilterTextBox.Text) Then
XPath = "/lexique/item"
Else
XPath = "/lexique/item[starts-with(#acronym, '" + FilterTextBox.Text + "')]"
End If
LexiqueXmlDataSource.XPath = XPath
LexiqueXmlDataSource.DataBind()
LexiqueGrid.DataSource = LexiqueXmlDataSource
LexiqueGrid.DataBind()
Hits.Text = "Selected " & LexiqueGrid.Rows.Count & " out of " &
LexiqueXmlDataSource.GetXmlDocument.ChildNodes.Count & "Acronyms loaded."
End Sub
End Class

If I understand correctly you want to know the number of returned elements. Would the XPath expression 'count(Some_XPath_here)' not give this number of hits ?

here is some code and the scenario I
want:
protected void Page_Load(object sender, EventArgs e)
{
string xpath = "/lexique/item[starts-with(#acronym, '" + filter + "')]";
LexiqueXmlDataSource.XPath = xpath;
// Here the XmlDataSource have filtered the xml elements to return to the GridView
//I want to know how many element passed this filter using the XmlDataSource itself
}
Just use and evaluate this XPath expression:
string xpath2 = "count(/lexique/item[starts-with(#acronym, '" + filter + "')])";

Related

RangeValidator in WebForms Page Fails with error

I have been tasked with maintaining an older webforms application without much training or experience.
I was asked to add a new field to an existing table and expose it in the web page. Here's the code to do that, which I modeled on other existing fields and code.
<asp:TextBox ID="PortableBarrelCompressionValuetextBox"
runat="server"
SkinID="FVTextBox"
Text='<%# Bind("PortableBarrelCompressionValue") %>'
<asp:RangeValidator
ID="RangeValidatorPortableBarrelCompressionValuetextBox"
runat="server"
ControlToValidate="PortableBarrelCompressionValuetextBox"
CssClass="failureNotification"
Display="Dynamic"
ErrorMessage="Whole Numbers Between 0 and 9999"
MaximumValue="9999"
MinimumValue="0"
Type="Integer"
Text='<%# Eval("PortableBarrelCompressionValue") %>'>
</asp:RangeValidator>
This only works correctly when the existing value is non-null (and of course, within range). If I change a valid number, say 22, to a different valid number, 200, it saves the change as expected.
However, if the value on an existing record was null and I try to add an integer, it fails with the error message:
Value {" is not a valid value for Int32."} System.Exception
It also fails if there is an existing, valid, value which deleted, with the same error.
This field is not required, so I have to allow for Nulls here.
I've learned enough in the last two days to decide this is happening because the field is an integer and that the Null can't be converted to a string for the validation (at least that's what I'm assuming now).
If that is true, and this is the problem, I need to find a way to resolve that.
Am I on the right track?
Is there a way to provide a validation that will also accept nulls in this field, in addition to integers in the proper range?
Thanks in advance.
This does not throw your error
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="FredWebForm.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<%--bind only used with controls that have datasource eg grid--%>
<asp:TextBox runat="server" Text='<%# GetStatus("PortableBarrelCompressionValue") %>' ID="MyTextBox" />
<asp:RangeValidator
ID="RangeValidatorPortableBarrelCompressionValuetextBox"
runat="server"
ControlToValidate="MyTextBox"
CssClass="failureNotification"
Display="Dynamic"
ErrorMessage="Whole Numbers Between 0 and 9999"
MaximumValue="9999"
MinimumValue="0"
Type="Integer"
Text='Needs to be a number between 0 and 9999'>
</asp:RangeValidator>
</asp:Content>
Code behind
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
protected string GetStatus(string theID)
{
return null;
}
}
I finally figured out my error.
It was not in this section at all.
I didn't realize that the definition of the LingDataSource for the form has to be updated as well.
Once I added this line:
<asp:Parameter Name="PortableBarrelCompressionValue"
ConvertEmptyStringToNull="true" />
It came back to life.
Thanks for all the support.

Mono on Apache2 System.Web.Compilation.CompilationException: VBNC30451: Could not resolve the name 'Type'

I installed mono and mod_mono for apache2 running on Debian 7.
Though its giving me this error:
System.Web.Compilation.CompilationException
VBNC30451: Could not resolve the name 'Type'
Description: Error compiling a resource required to service this request. Review your source file and modify it to fix this error.
Details: VBNC30451: Could not resolve the name 'Type'
Error origin: Compiler
Error source file: /tempconvert.asmx
Exception stack trace:
at System.Web.Compilation.AssemblyBuilder.BuildAssembly (System.Web.VirtualPath virtualPath, System.CodeDom.Compiler.CompilerParameters options) [0x0035f] in /home/joaogl/mono-3.4.0/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs:853
at System.Web.Compilation.AssemblyBuilder.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000] in /home/joaogl/mono-3.4.0/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs:731
at System.Web.Compilation.BuildManager.GenerateAssembly (System.Web.Compilation.AssemblyBuilder abuilder, System.Web.Compilation.BuildProviderGroup group, System.Web.VirtualPath vp, Boolean debug) [0x00258] in /home/joaogl/mono-3.4.0/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs:846
at System.Web.Compilation.BuildManager.BuildInner (System.Web.VirtualPath vp, Boolean debug) [0x0011c] in /home/joaogl/mono-3.4.0/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs:469
How can I solve this?
If I understand the nature of your problem (I have had the same problem), then:
Follow this (https://library.linode.com/frameworks/mod-mono/debian-5-lenny) "mod_mono and Apache on Debian" installation instruction
Use this (http://go-mono.com/config-mod-mono/Default.aspx) to generate an Apache mod_mono configuration file.
If you have set up MonoServerPath whatever "/usr/bin/mod-mono-server2" in your apache2.conf - remove it
Then, you may test how if it works.
Create index.aspx and put it into your htdocs directory or how you call it
<%# Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
//initialize a datetime variable with current datetime
DateTime now = DateTime.Now;
Label1.Text = "now : " + now.ToString();
//add 2 minutes to current time
DateTime dateAfter2Minutes = now.AddMinutes(2);
TimeSpan ts = dateAfter2Minutes - now;
//total milliseconds difference between two datetime object
int milliseconds = (int)ts.TotalMilliseconds;
Label1.Text += "<br ><br />after two minutes: ";
Label1.Text += dateAfter2Minutes.ToString();
Label1.Text += "<br ><br />smillieconds difference between to datetime object : ";
Label1.Text += milliseconds;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>c# example - datetime difference in milliseconds</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - datetime difference in milliseconds
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
Font-Names="Comic Sans MS"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="get milliseconds difference between two datetime"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>
It helped me.
Good luck!
apache2monomod-monodebianasp.netcompilation

How to Preview uploaded image using telerik RadAsyncUpload and RadBinaryImage in ASP Update Panel?

I have a web form in asp.net contains a RadAsyncfileupload and a RadBinaryImage inside an Asp Update Panel like following
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<telerik:RadAsyncUpload ID="RadAsyncUpload1" runat="server">
</telerik:RadAsyncUpload>
<telerik:RadBinaryImage ID ="RadBinaryImage1" runat ="server" Width= "100px" Height="100px"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
in code behind
protected void RadAsyncUpload1_FileUploaded(object sender, Telerik.Web.UI.FileUploadedEventArgs e)
{
if (RadAsyncUpload1.UploadedFiles.Count == 1)
{
byte[] image;
long fileLength = RadAsyncUpload1.UploadedFiles[0].InputStream.Length;
image = new byte[fileLength];
RadAsyncUpload1.UploadedFiles[0].InputStream.Read(image, 0, image.Length);
RadBinaryImage1.DataValue = image;
}
}
but in runtime program controller does not fire RadAsyncUpload1_FileUploaded event
I have searched the Telerik forum and found that I should do something to script manager but I need some help on how to do it the reason is that in order to fire this event whole page should post back anyway some scripts can help me or any other ways!
mention that I need byte array of the image to save it in DB.
Thanks in advance
Saeed Soleimanifar
http://demos.telerik.com/aspnet-ajax/asyncupload/examples/persistuploadedfiles/defaultvb.aspx?#qsf-demo-source
I just added the same functionality by using this , if you find any problem let me know...
OR
Here is the part that does the magic
Page Source :
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function updatePictureAndInfo() {
__doPostBack('btnImgUpload', 'RadButton1Args');
}
</script>
</telerik:RadScriptBlock>
<telerik:RadBinaryImage runat="server" ID="imgBinaryPhoto" ImageUrl="~/Images/default-profile-pic.png"
Width="100px" Height="100px" ResizeMode="Fit" AlternateText="No picture available"
CssClass="preview"></telerik:RadBinaryImage>
<br />
<telerik:RadAsyncUpload ID="upldPhoto" runat="server" AllowedFileExtensions=".jpg,.png,.gif,jpeg,.tiff"
MaxFileInputsCount="1" MultipleFileSelection="Disabled">
</telerik:RadAsyncUpload>
<asp:Button ID="btnImgUpload" runat="server" Text="Upload" CssClass="button" OnClientClick="updatePictureAndInfo(); return false;" />
Code Behind:
Protected Sub FileUploaded() Handles upldPhoto.FileUploaded
Dim bitmapImage As Bitmap = ResizeImage(upldPhoto.UploadedFiles(0).InputStream)
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)
imgBinaryPhoto.DataValue = stream.ToArray()
End Sub

Only one instance of a ScriptManager can be added

Why do I get this error message: Only one instance of a ScriptManager can be added to the page?
I haven't been using HTML comment to hide an ASP.NET server tag and there is no other ScriptManager in the entire project.
Markup:
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblCount" CssClass="LikeCount" Text='<%#Eval("LikeCount") %>' runat="server"></asp:Label>
<asp:LinkButton ID="lbAddOne" CssClass="LikeAddOne" Text="+1" runat="server" OnClick="lbAddOne_Click" CommandArgument='<%#Eval("ReviewID") %>'></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
Code-behind:
protected void lbAddOne_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
string ReviewID = _sender.CommandArgument;
int UserID = ((User)Session["LoggedInUser"]).UserID;
lblCount.Text = (int.Parse(lblCount.Text) + 1).ToString();
CategoryAccess.AddLikeReview(ReviewID, UserID);
}
just add a reference to scriptmanager in the masterpage, then it will be available to any page referencing the master. this will be easier to maintain in the long run rather than adding references to individual pages.

Add javascript to generated html test page for Silverlight project

VS2010, Silverlight 4.0.
Does anyone know if there is a way to have Visual Studio add javascript (or anything for that matter) to the html test page it generates when compiling a silverlight project for debug? Does it use a template, and if so, where is it?
Really interesting question!
I've tried to do something like that and finally found raw but pretty working solution:
First of all you should set specific page by using Properties -> Debug -> Specific Page.
My page example:
<!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>
<title>SilverlightApplication1</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="fillWithData">
</div>
<form id="form1" runat="server" style="height:100%">
<div id="silverlightControlHost" style="height: 100%; text-align:center">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="30%" height="30%">
<param name="source" value="file:///C:/Users/Igor/Documents/Visual Studio 2010/Projects/MobileTest/SilverlightApplication1/Bin/Debug/SilverlightApplication1.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
</form>
</body>
</html>
NOTE: blank script and div elements is important! we'll load dynamic js/html into them.
My silverlight xaml.cs:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HtmlDocument hostPage = HtmlPage.Document;
ScriptObject obj = hostPage.GetElementsByTagName("script")[0];
obj.SetProperty("innerHTML", "function alertonclick() { alert('Amazing! I am dynamic javascript!'); }");
HtmlElement ipAddressHtml = hostPage.GetElementById("fillWithData");
ipAddressHtml.SetProperty("innerHTML", #"<input id=""Button1"" type=""button"" value=""button"" onclick=""alertonclick();"" />");
}
}
VERY IMPORTANT NOTE: I've tested this code and it works only under Opera.
If you need to test something using some other browser then you sould inline javascript directly into element.
Example:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HtmlDocument hostPage = HtmlPage.Document;
HtmlElement ipAddressHtml = hostPage.GetElementById("fillWithData");
ipAddressHtml.SetProperty("innerHTML", #"<input id=""Button1"" type=""button"" value=""button"" onclick=""alert('Amazing! I am dynamic javascript!');"" />");
}
}
This code works well under IE/FF/Chrome/Opera (of course :) ).
As for me I like first example with both dynamic js and html. And I'm pretty sure that it's possible to fix it and make acceptable by other browser not just Opera.
I hope that my examples will help you =)

Resources