Below is the code that is causing the error. As a newbie to XSL and ASP.NET, I don't quite understand why the error is occurring...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="view.aspx.cs" Inherits="ININ.Marquee.Web.view" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Configuration" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Xml.XPath" %>
<%# Import Namespace="System.Xml.Xsl" %>
<!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" >
<html>
<head>
</head>
<body>
<form id="form1" runat="server" >
<div>
<script runat="server">
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
public static string GetHtml(string xsltPath, string xml)
{
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));
XPathDocument document = new XPathDocument(stream);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);
transform.Transform(document, null, writer);
return writer.ToString();
}
public string details = string.Empty;
private void Page_Load(object sender, EventArgs e)
{
/******** - This the START of all the Database Stuff - ********/
// Create a String to hold the database connection string.
// NOTE: Put in a real database connection string here or runtime won't work
string sdwConnectionString = #"Data Source = server; user id=username; password=password; Initial Catalog = database;";
// Create a connection
SqlConnection sdwDBConnection = new SqlConnection(sdwConnectionString);
// Open the connection
sdwDBConnection.Open();
// Create a String to hold the query.
string query = "SELECT * from IWrkgrpQueueStats WHERE ((substring(convert(char,dIntervalStart,120),1,10) = substring(convert(char,getdate(),120),1,10)) AND (cName IN ('Password','Arbour/CMBS/Other','Incident Escalation', 'OPOM/SOS/MyAccount','PC/Outlook','Overflow')) AND (cReportGroup='*' AND cHKey3='*' AND cHKey4='*'))";
// Create a SqlCommand object and pass the constructor the connection string and the query string.
SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);
// Use the above SqlCommand object to create a SqlDataReader object.
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Create a DataTable object to hold all the data returned by the query.
DataTable duplicatedataTable = new DataTable();
// Use the DataTable.Load(SqlDataReader) function to put the results of the query into a DataTable.
duplicatedataTable.Load(queryCommandReader);
// Open the connection
sdwDBConnection.Close();
DataSet ds = new DataSet("interactions");
ds.Tables.Add(duplicatedataTable);
string XML = ds.GetXML();
details=GetHtml(Server.MapPath("~/Test.xsl"), XML);
}
</script>
<table width="100%">
<tr>
<td align="left">
<table width="100%" border="0">
<tr bgcolor="Silver">
<th align="center">
<%= details %>
</th>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I have reviewed both this code and the .xsl code and there doesn't appear to be any issues. Can anyone please explain what the error means and where the issue causing the error would occur? Thanks for your assistance.
I believe your problem is one of case-sensitivity.
Why don't you try:
string XML = ds.GetXml();
rather than
string XML = ds.GetXML();
Hope that helps.
Related
<form id="Form1" runat="server">
**<input type="text" id="DateInput" />**
<asp:Repeater ID="DataViewer" runat="server">
<ItemTemplate>
<div style='border: 1px; width: 600px; overflow-x: auto; overflow-y: hidden;'>
<div style='float: left;'>
<%# Eval("DriverName") %> </div>
</div>
</ItemTemplate>
</asp:Repeater>
this is my function:
protected void Page_Load(object sender, EventArgs e)
{
OrderDataRepository rep = new OrderDataRepository();
var results = rep.GetAllOrderData().Where(x => x.POD_DATE == ????????????????).
GroupBy(o => o.User).
Select(g =>
new
{
DriverId = g.Key.Id,
DriverName = g.Key.Name,
OrderCount = g.Count(),
OrderCountWhereNameIsNotNull =
g.Count(o => o.RECEIVE_NAME != null)
}).ToList();
DataViewer.DataSource = results;
DataViewer.DataBind();
}
at the moment i get all the results from the table,
i want to add Datepicker for jQuery http://keith-wood.name/datepick.html
<script src="Scripts/jquery.js" type="text/javascript"></script>
when user will pick a day it needs to load all the results for the day that the user picked
please show me how it should be done using jquery with entity framework
You'll need a function in your repository some thing like:
Function SelectOrdersByDate(date as string) as ienumerable(of Order)
Using yourcontext as new context
Dim query = yourcontext.Orders.Where(function(o) o.OrderDate = date).ToList
return query
End Using
End Function
Then call this function via ajax/jquery
Hey all, i have this peice of code that allows a user to select a jpg image, resize it and uploads it to the server driectory. The problem being is that it reloads the aspx page when it saves the image.
My question is-is there any way to do this same thing but with ajax so that it doesn't leave the page after submitting it? I've done this pleanty of times with classic asp pages but never with a aspx page.
Here is the code for the ASPX page:
<%# Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
<%# Import Namespace=System.Drawing %>
<%# Import Namespace=System.Drawing.Imaging %>
<%# Import Namespace=System.Drawing.Text %>
<%# Import Namespace=System %>
<%# Import Namespace=System.IO %>
<%# Import Namespace=System.Web %>
<%# Import Namespace=System.ServiceProcess %>
<%# Import Namespace=Microsoft.Data.Odbc %>
<%# Import Namespace=System.Data.Odbc %>
<%# Import Namespace=MySql.Data.MySqlClient %>
<%# Import Namespace=MySql.Data %>
<%# Import Namespace=System.Drawing.Drawing2D %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.ADO" %>
<%# Import Namespace=ADODB %>
<SCRIPT LANGUAGE="VBScript" runat="server">
const Lx = 200
const Ly = 60
const upload_dir = "/img/avatar/"
const upload_original = "tmpAvatar"
const upload_thumb = "thumb"
const upload_max_size = 256
dim fileExt
dim newWidth, newHeight as integer
dim l2
dim fileFld as HTTPPostedFile
Dim originalimg As System.Drawing.Image
dim msg
dim upload_ok as boolean
</script>
<%
Dim theID, theEmail, maleOrFemale
theID = Request.QueryString("ID")
theEmail = Request.QueryString("eMail")
maleOrFemale = Request.QueryString("MF")
randomize()
upload_ok = false
if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then
fileFld = request.files(0)
if fileFld.ContentLength > upload_max_size * 1024 then
msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
else
try
fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
if fileExt = ".jpg" then
originalImg = System.Drawing.Image.FromStream(fileFld.InputStream)
if originalImg.Height > Ly then
newWidth = Ly * (originalImg.Width / originalImg.Height)
newHeight = Ly
end if
Dim thumb As New Bitmap(newWidth, newHeight)
Dim gr_dest As Graphics = Graphics.FromImage(thumb)
dim sb = new SolidBrush(System.Drawing.Color.White)
gr_dest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
gr_dest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height)
try
originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat)
thumb.save(Server.MapPath(upload_dir & theID & fileExt), originalImg.rawformat)
msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
upload_ok = true
File.Delete(Server.MapPath(upload_dir & upload_original & fileExt))
catch
msg = "Sorry, there was a problem saving your avatar. Please try again."
end try
if not thumb is nothing then
thumb.Dispose()
thumb = nothing
end if
else
msg = "That image does not seem to be a JPG. Upload only JPG images."
end if
catch
msg = "That image does not seem to be a JPG."
end try
end if
if not originalImg is nothing then
originalImg.Dispose()
originalImg = nothing
end if
end if
%><head>
<meta http-equiv="pragma" content="no-cache" />
</head>
<html>
<script type="text/javascript" src="js/jquery-1.3.min.js"></script>
<form enctype="multipart/form-data" method="post" runat="server" id="sendImg">
<input type="file" name="upload_file" id="upload_file" style="-moz-opacity: 0; opacity:0; filter: alpha(opacity=0); margin-top: 5px; float:left; cursor:pointer;" onChange="$('#sendImg').submit();" >
<input type="submit" value="Upload" style="visibility:hidden; display:none;">
</form>
</body>
</html>
Any help would be great! :o)
David
ajax and <input type="file"> don't work well together. the underlying XMLHttpRequest object is restricted and can't actually access the file upload. There is a very limited set of things that you can do with any javascript as it pertains to the file upload. The easiest way to fake what you are trying to do is use an iframe.
I am using a server control on a single web.forms page. I have to use this control on a web.forms page since its a server control, although this is actually a MVC project. So I created a web.forms folder and put my new page in it. I then copy the example code from the signature control. I get the following error:
The base class includes the field 'ctrlSign', but its type (WebSignatureCapture.SignatureControl) is not compatible with the type of control (ASP.signaturecapture_signaturecontrol_ctlsignature_ascx).
I know the code works because if I removed the ID attribute from the server control, it no longer gives me this error and my control renders. But I need the attribute for the ID so I can perform is post event... Any ideas why?
I am using this signature control. Here's the web.forms code...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="KahunaCentralTIDRevamp.SignatureCapture.Index" %>
<%# Reference Control="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<%# Register TagPrefix="uc" TagName="Signature" Src="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Signature Application Demo</title>
</head>
<body>
<form id="frmOrder" method="post" runat="server">
<div>
Please Sign Below:
</div>
<div>
<uc:Signature ID="ctrlSign" SignHeight="150" SignWidth="300" SignatureCodePath="~/SignatureCapture/SignatureControl/"
SavePath="~/SignatureCapture/" SignatureFileFormat="Gif" runat="server" />
<%-- <uc:Signature id="ctlMySignature" PenColor="Red" PenWidth="2" BackColor="Yellow" SignWidth="300" SignHeight="150"
SavePath="~/Signatures/" SignatureCodePath="~/SignatureControl/" SignatureFileFormat="Gif" Runat="server"></uc:Signature>--%>
</div>
<div>
<input type="button" value=" Re-Sign " onclick="ClearSignature();">
<asp:Button runat="server" ID="btnSave" Text=" Save " onmousedown="document.getElementById('btnSave').value = 'Wait...';"
OnClientClick="DirectSave();" OnClick="btnSave_Click" />
</div>
</form>
<script language="javascript" type="text/javascript">
// This is the method that is directly called, this will save signature
// and then call server code to do further processing. You can change
// the delay of 5 seconds as per your needs
function DirectSave() {
SaveSignature();
var date = new Date();
var curDate = null;
// delay of 5 seconds, 5000 milisecons, change as per requirement
do { curDate = new Date(); }
while (curDate - date < 5000);
return true;
}
</script>
</body>
</html>
Open the .ascx markup file of the user control. It should read something like this:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeFile="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Modify it to:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeBehind="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Notice CodeFile -> CodeBehind.
Someone I know had a similar problem a while back, and then they found something that they could do something in the BeginRequest which sorted his problem and allowed him to use server controls in views. I did a quick search for it, and I believe that this is what he used.
Code below:
void Application_BeginRequest(object sender, EventArgs e)
{
var form = HttpContext.Current.Request.Form;
form.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(form, false, null);
// Refinement 1:
foreach (var key in form.AllKeys.Where(key => key.Contains("$")))
{
var value = formkey;
form.Remove(key);
var newKey = key.Substring(key.LastIndexOf("$") + 1);
form.Add(newKey, value);
}
}
I want to create a MVC 2 editor template for a value type i.e. int , has anyone done this with the preview 1 bits?
Many thanks
Will Nick Clarke's answer work when you submit the values on postback?
In MVC2 preview 2, calling Html.Textbox("abc", Model.ToString())
will render a textbox with ".abc" appended to the name, e.g.
<input id="StartDate_abc" name="StartDate.abc" type="text" value="02 Feb 09" />
which will cause problems when you postback and attempt to UpdateModel().
I did an editor template for a DateTime, the following works for me:
/Views/Shared/EditorTemplates/DateTime.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%= Html.TextBox(String.Empty, Model.ToString("dd MMM yy")) %>
or, to use jQuery's DatePicker for all your DateTimes
add a reference to jQuery and jQueryUI to either your Masterpage or to the View containing the call to EditorFor.
/Views/Shared/EditorTemplates/DateTime.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%= Html.TextBox("", Model.ToString("dd MMM yy")) %>
<script type="text/javascript">
$("#<%= ViewData.ModelMetadata.PropertyName %>").datepicker({ dateFormat: 'dd M y' });
</script>
Update: ASP.NET MVC3, using the Razor syntax:
#model System.DateTime
#Html.TextBox("", Model.ToString("dd MMM yy"))
<script type="text/javascript">
$("##ViewData.ModelMetadata.PropertyName").datepicker({ dateFormat: 'dd M y' });
</script>
And to use it all you need in your View is:
#Html.EditorFor(model => model.DueDate)
-Matt
I have not tried preview 1 yet but they did what you are asking for in this channel9 video:
http://channel9.msdn.com/posts/Glucose/Hanselminutes-on-9-ASPNET-MVC-2-Preview-1-with-Phil-Haack-and-Virtual-Scott/
They do both DisplayFor and EditorFor, starts around 2 minutes.
--Edit--
For value type i.e. int I was able to get it to work in the same way.
Create a model to pass to my view:
public class HomeController : Controller
{
public ActionResult Index()
{
HomeModel model = new HomeModel();
model.message = "Welcome to ASP.NET MVC!";
model.number = 526562262;
model.Date = DateTime.Now;
return View(model);
}
}
public class HomeModel
{
public string message { get; set; }
public int number { get; set; }
public DateTime Date { get; set; }
}
Link view to the model using the new template logic:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HomeModel>" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<p>
<% Html.EditorFor(c => c.message); %>
</p>
<p>
<% Html.EditorFor(c => c.number); %>
</p>
<p>
<% Html.EditorFor(c => c.Date); %>
</p>
Then create a template for each of the types e.g. Int32:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
Editor For My Int32: <%= Html.TextBox("abc", Model.ToString())%>
I put this in Views\Shared\EditorTemplates\Int32.ascx
I've written a blog post about how to do this by creating reusable templates in MVC 2.
My post also explains the relationship between TemplateInfo and templates.
I have found Brad Wilson's blog to have the best examples and explanations. Part-3 of the series talks specifically about value types (String, decimal, Int32).
Enjoy!
I have HTML table on the ASP.NET MVC View page. Now I have to export this table to Excel.
(1) I have used partial view (Inquiries.ascx) to display the table data from database (using LINQ to Entity)
(2) I also have used UITableFilter plugin to filter the records (Ex: http://gregweber.info/projects/demo/flavorzoom.html )
(3) At any point of time, I have to filter the visible records to Excel.
Appreciate your responses.
Thanks
Rita
Here is my View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mvc.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content2" ContentPlaceHolderID="cphHead" runat="server">
<script src="../../Scripts/jquery.tablesorter.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.uitablefilter.js" type="text/javascript"></script>
<script type="text/javascript">
//Load Partial View
$('#MyInquiries').load('/Home/Inquiries');
// To Apply Filter Expression using uiTableFilter plugin
$("#searchName").keyup(function() {
$.uiTableFilter($("#tblRefRequests"), this.value);
$("#tblRefRequests").tablesorter({ widthFixed: true, widgets: ['zebra'] });
});
//Export the HTML table contents to Excel
$('#export').click(function() {
//Code goes here
});
</script>
</asp:Content>
//Main Content
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" runat="server">
<h2 class="pageName">View All Inquiries</h2>
<input type="submit" value="Export to Excel" id="export" />
<div id='MyInquiries'></div>
</asp:Content>
Strongly Typed Partial view user control (Inquiries.ascx) to generate table:
<table>
<tr><td valign ="middle">Filter Expression: <%= Html.TextBox("searchName")%></td></tr>
</table>
<table id="tblRefRequests" >
<thead>
<tr>
<th>Tx_ID</th>
<th>TX Date</th>
<th>Name</th>
<th>Email Address </th>
<th>Products</th>
<th>Document Name</th>
</tr>
</thead>
<tbody>
<% foreach (var item in Model) { %>
<tr>
<td visible =false><%= item.RequestID %></td>
<td><%= String.Format("{0:d}", item.RequestDate) %></td>
<td><%= item.CustomerName %></td>
<td><%= Html.Encode(item.Email) %></td>
<td><%= item.ProductName %></td>
<td><%= Html.Encode(item.DocDescription)%></td>
</tr>
<% } %>
</tbody>
</table>
Here is my Controller code to load the Inquiries partial view:
[HttpGet]
public PartialViewResult Inquiries()
{
var model = from i in myEntity.Inquiries
where i.User_Id == 5
orderby i.TX_Id descending
select new {
RequestID = i.TX_Id,
CustomerName = i.CustomerMaster.FirstName,
RequestDate = i.RequestDate,
Email = i.CustomerMaster.MS_Id,
DocDescription = i.Document.Description,
ProductName = i.Product.Name
};
return PartialView(model);
}
Try the jQuery plugin: table2csv. Use the argument, delivery:'value', to return the csv as a string.
Here is an implementation:
Add a regular html input button and a .NET HiddenField to the page
Add an onclick event to that button called "Export"
Create a javascript function, Export, that stores the return value of table2CSV() into the hidden field, and posts back.
The server receives the hiddenfield post data (the csv as a string)
The server outputs the string to the browser as a csv file
.
// javascript
function Export()
{
$('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});
__doPostBack('#yourExportBtnId', '');
}
// c#
if(Page.IsPostBack)
{
if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))
{
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");
Response.Flush();
Response.Write(Request.Form[yourHiddenField.UniqueID]);
Response.End();
}
}
download components:npm install table-to-excel
https://github.com/ecofe/tabletoexcel
var tableToExcel=new TableToExcel();
document.getElementById('button1').onclick=function(){
tableToExcel.render("table");
};
document.getElementById('button2').onclick=function(){
var arr=[
['LastName','Sales','Country','Quarter'],
['Smith','23','UK','Qtr 3'],
['Johnson','14808','USA','Qtr 4']
]
tableToExcel.render(arr,[{text:"create",bg:"#000",color:"#fff"},{text:"createcreate",bg:"#ddd",color:"#fff"}]);
};