combining between scripts - c#

DriverId OrderCount OrderCountWhereNameIsNotNull
12 2 2
13 1 1
this is the current table which is being made by this code:
public partial class Control : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OrderDataRepository rep = new OrderDataRepository();
var results = rep.GetAllOrderData().
GroupBy(o => o.DRIVER_ID).
Select(g =>
new
{
DriverId = g.Key,
OrderCount = g.Count(),
OrderCountWhereNameIsNotNull =
g.Count(o => o.RECEIVE_NAME != null)
}).ToList();
DataViewer.DataSource = results;
DataViewer.DataBind();
}
}
instead of the table I need to take and print for each DriverId a progress bar as in this script:
int OrderCount, OrderCountWhereNameIsNotNull;
System.Web.UI.WebControls.TableRow oRow;
System.Web.UI.WebControls.TableCell oCell;
System.Web.UI.HtmlControls.HtmlGenericControl oDiv;
while (true)
//loop through records
//do while not eof
{
oRow = new System.Web.UI.WebControls.TableRow();
oCell = new System.Web.UI.WebControls.TableCell();
oDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
OrderCount = 200; //get value from DB, convert to meaningful width
OrderCountWhereNameIsNotNull = 100; //get value from DB, convert to meaningful width
oDiv.InnerHtml = "<div style='border: 3px solid black; width: " + OrderCount + "px;'>";
oDiv.InnerHtml += Environment.NewLine + " <div style='border: 0px; background-color: red; width: " + OrderCountWhereNameIsNotNull + "px;'> </div>";
oDiv.InnerHtml += Environment.NewLine + "</div>";
oCell.Controls.Add(oDiv);
oRow.Cells.Add(oCell);
tblData.Rows.Add(oRow);
}
I cannot combine them, may be the script is not good...please help
at the moment my main page is:
<form id="Form1" runat="server">
<asp:GridView runat="server" ID="DataViewer">
</asp:GridView>
</form>

You will probably find it simpler to bind your grid to your dataset, rather than building a table that attempts to inject itself into a grid:
<asp:GridView ID="DataViewer" runat="server">
<Columns>
<TemplateColumn>
<ItemTemplate>
Put the code for rendering your progress bar here in pure HTML.
When you come to a value that will come from a row in your data, do like this:
<div style='width: <%# Eval("OrderCount") %>' />
</ItemTemplate>
</TemplateColumn>
</Columns>
</asp:GridView>

Related

How to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within..." question?

How to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within current table only" question ?
Because I try coding with sample but can't select all asp:CheckBoxList within current table only.
Link to "JQuery - Select All CheckBoxes within current table only" question.
My snipplet to describe problem.
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript"
src="//code.jquery.com/jquery-1.6.4.js"></script>
<style>
form , p , td, th{
font-size: 24px;
}
input.largerCheckbox
{
width: 22px;
height: 22px;
}
</style>
</head>
<body>
<h1>Show checkboxes:</h1>
<p><label><input type="checkbox" class="largerCheckbox" id="checkAll"/> Check all</label></p>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"><br><br>
<table id="myTable">
<tr class="header">
<th>Checkbox</th>
<th>Number</th>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle1" value="1"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle2" value="11"></td>
<td>11</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle3" value="111"></td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle4" value="1111"></td>
<td>1111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle5" value="11111"></td>
<td>11111</td>
</tr>
</table>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
</script>
</body>
</html>
My full source code.
https://github.com/doanga2007/CheckLoopQR3
Sample code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR3.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
#myInput {
font-size: 16px;
padding: 6px 20px 6px 10px;
border: 1px solid #ddd;
margin-bottom: 3px;
}
</style>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("CheckBox1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<label>Input Number to Search </label>
<input type="text" id="myInput" onkeyup="myFunction()"><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR3
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 6; i++)
{
num *= i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Text 1 -> ", "Selected Text 2 -> ", "Selected Text 3 -> ",
"Selected Text 4 -> ", "Selected Text 5 -> "};
string[] texture2 = { " is Checkbox 1.", " is Checkbox 2.", " is Checkbox 3.",
" is Checkbox 4.", " is Checkbox 5."};
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
int a = CheckBox1.Items.IndexOf(listItem);
a = a + 1;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a - 1] + listItem.Text + texture2[a - 1];
lblvalues.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}
Good news : I have answer to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within current table only" question.
Key of answer to "jQuery :visible Selector".
jQuery :
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
});
My snipplet to another solve problem in HTML.
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript"
src="//code.jquery.com/jquery-1.6.4.js"></script>
<style>
form , p , td, th{
font-size: 24px;
}
input.largerCheckbox
{
width: 22px;
height: 22px;
}
</style>
</head>
<body>
<h1>Show checkboxes:</h1>
<p><label><input type="checkbox" class="largerCheckbox" id="checkAll"/> Check all</label></p>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"><br><br>
<table id="myTable">
<tr class="header">
<th>Checkbox</th>
<th>Number</th>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle1" value="1"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle2" value="11"></td>
<td>11</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle3" value="111"></td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle4" value="1111"></td>
<td>1111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle5" value="11111"></td>
<td>11111</td>
</tr>
</table>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
</script>
</body>
</html>
My full source code.
https://github.com/doanga2007/CheckLoopQR3
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR3.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
#myInput {
font-size: 16px;
padding: 6px 20px 6px 10px;
border: 1px solid #ddd;
margin-bottom: 3px;
}
</style>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
});
</script>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("CheckBox1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<label>Input Number to Search </label>
<input type="text" id="myInput" onkeyup="myFunction()"><br />
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR3
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 6; i++)
{
num *= i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Text 1 -> ", "Selected Text 2 -> ", "Selected Text 3 -> ",
"Selected Text 4 -> ", "Selected Text 5 -> "};
string[] texture2 = { " is Checkbox 1.", " is Checkbox 2.", " is Checkbox 3.",
" is Checkbox 4.", " is Checkbox 5."};
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
int a = CheckBox1.Items.IndexOf(listItem);
a = a + 1;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a - 1] + listItem.Text + texture2[a - 1];
lblvalues.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}

Image and back color is not printing with Cross browser rdlc report printing with report viewer control in Asp.Net

to implement print feature for rdlc report in report viewer control in asp.net mvc web app, I followed this solution. It worked for me https://stackoverflow.com/a/14052577/870561.
this jquery script adds a print button in report viewer toolbar and on click shows a print preview dialogue that is cool. But it is not adding images and back color styles in print.
Please suggest a way to include images which are used in rdlc reports and also back colors. My code is attached below.
function pageLoad() {
try {
if (!$("#ff_print").length) {
var ControlName = 'ReportViewer1';
var innerTbody = '<tbody><tr><td><input type="image" style="border-width: 0px; padding: 2px; height: 16px; width: 16px;" alt="Print" src="/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=11.0.0.0&Name=Microsoft.Reporting.WebForms.Icons.Print.gif" title="Print"></td></tr></tbody>';
var innerTable = '<table title="Print" onclick="PrintFunc(\'' + ControlName + '\'); return false;" id="ff_print" style="border: 1px solid rgb(236, 233, 216); background-color: rgb(236, 233, 216); cursor: default;">' + innerTbody + '</table>'
var outerDiv = '<div style="display: inline; font-size: 8pt; height: 30px;" class=" "><table cellspacing="0" cellpadding="0" style="display: inline;"><tbody><tr><td height="28px">' + innerTable + '</td></tr></tbody></table></div>';
$("#ReportViewer1_ctl05 > div").append(outerDiv);
}
}
catch (e) { alert(e); }
}
function PrintFunc() {
var strFrameName = ("printer-" + (new Date()).getTime());
var jFrame = $("<iframe name='" + strFrameName + "'>");
jFrame
.css("width", "1px")
.css("height", "1px")
.css("position", "absolute")
.css("left", "-2000px")
.appendTo($("body:first"));
var objFrame = window.frames[strFrameName];
var objDoc = objFrame.document;
var jStyleDiv = $("<div>").append($("style").clone());
objDoc.open();
objDoc.write($("head").html());
objDoc.write($("#VisibleReportContentReportViewer1_ctl09").html());
objDoc.write("<style>#page { size: auto; margin:5mm } </style>")
objDoc.close();
objFrame.print();
setTimeout(function () { jFrame.remove(); }, (60 * 1000));
}
The following points are taking effect
1. CSS For back colors add css -webkit-print-color-adjust: exact. for more info
2. to print Images you need add this css property to img tag or div which contains the image. display:block; or visibility:visible
3. Chrome does not load images quickly, so you have to add pause before print. This hack worked for me.
The final solution I got this:
function PrintFunc() {
var strFrameName = ("printer-" + (new Date()).getTime());
var jFrame = $("<iframe name='" + strFrameName + "'>");
jFrame
.css("width", "1px")
.css("height", "1px")
.css("position", "absolute")
.css("left", "-2000px")
.appendTo($("body:first"));
var objFrame = window.frames[strFrameName];
var objDoc = objFrame.document;
var jStyleDiv = $("<div>").append($("style").clone());
objDoc.open();
objDoc.write($("head").html());
objDoc.write($("#VisibleReportContentReportViewer1_ctl09").html());
var style = "<style>";
style = style + "#page { size: auto; margin: 0.845in 1in 0.845in 1in }";
style = style + "#media print { body {-webkit-print-color-adjust: exact; } img{ visibility : visible; } }";
style = style + "</style>";
objDoc.write(style);
setTimeout(function () {
objDoc.close();
objFrame.print();
}, 750);
setTimeout(function () { jFrame.remove(); }, (60 * 1000));
}

How to align a GridView with different numbers of rows inside a DataList?

I'm developing a web application where users can register expenses and I have a page where I show a report of all the registers per day and these registers come from database.
To show these registers, I have a DataList in which the days are displayed, and below this, a GridView to display the registers.
Supposing that the user registered different numbers of expenses in different days, if I show the report to the user, the GridView is totally misaligned, because of the different number of rows; basically, I have a thing like this:
Is there some way to align the GridView to show the registers aligned?
I was able to replicate your issue on my side.All I did to fix it was to add this style rule to my page:
td
{
vertical-align:top;
}
Below is the complete example of displaying a GridView inside a DataList in ASP.NET web forms with alignment fixed.
Code behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
namespace WebApplication6
{
public partial class DataListAndGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add(new System.Data.DataColumn("ID", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Day", typeof(String)));
AddRow("0", "MONDAY", dt);
AddRow("1", "TUESDAY", dt);
AddRow("2", "WEDNESDAY", dt);
AddRow("3", "THURSDAY", dt);
AddRow("4", "FRIDAY", dt);
AddRow("5", "SATURDAY", dt);
AddRow("6", "SUNDAY", dt);
daysOfWeek.DataSource = dt;
daysOfWeek.DataBind();
}
private void AddRow(string id, string day, DataTable dt)
{
DataRow row;
row = dt.NewRow();
row[0] = id;
row[1] = day;
dt.Rows.Add(row);
}
private void BindGrid(GridView gv, int id)
{
gv.DataSource = this.GetRegisters(id);
gv.DataBind();
}
protected void daysOfWeek_ItemDataBound(object sender, DataListItemEventArgs e)
{
object dataKey = daysOfWeek.DataKeys[e.Item.ItemIndex];
int key = Convert.ToInt32(dataKey);
GridView gridResponses = (GridView)e.Item.FindControl("gvResponses");
BindGrid(gridResponses, key);
}
public List<Register> GetRegisters(int id)
{
List<Register> registers = new List<Register>();
registers.Add(new Register() { DayID = 0, FirstName = "Monday Name 1", LastName = "Monday Surname 1" });
registers.Add(new Register() { DayID = 0, FirstName = "Monday Name 2", LastName = "Monday Surname 2" });
registers.Add(new Register() { DayID = 1, FirstName = "Tuesday Name 1", LastName = "Tuesday Surname 1" });
registers.Add(new Register() { DayID = 1, FirstName = "Tuesday Name 1", LastName = "Tuesday Surname 2" });
return registers.Where(r => r.DayID == id).ToList();
}
}
public class Register
{
public int DayID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataListAndGrid.aspx.cs" Inherits="WebApplication6.DataListAndGrid" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
#dayContainer {
width: 250px;
height: 70px;
font-size: 20px;
border: 2px solid black;
text-align: center;
vertical-align: middle;
display:table-cell;
}
#gridContainer {
border: 2px solid black;
border-top: none;
width: 250px;
}
td
{
vertical-align:top;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="daysOfWeek" DataKeyField="ID" runat="server" RepeatDirection="Horizontal" OnItemDataBound="daysOfWeek_ItemDataBound">
<ItemTemplate>
<div style="float:left;">
<div id="dayContainer">
<%# DataBinder.Eval(Container.DataItem,"Day") %>
</div>
<div id="gridContainer">
<asp:GridView runat="server" ID="gvResponses" DataKeyNames="DayID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="125px" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="125px" />
</Columns>
</asp:GridView>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
Output:

Sitecore Feed latest 2 items

I have a sitecore web part that I am trying to get to display the top 2 most current items by date. I am having trouble because I am only able to get the latest item to show.
For the ascx Code:
<asp:Repeater ID="newsContainer" runat="server">
<ItemTemplate>
<div class="newsItem">
<h2>News</h2>
<a href="<%# SitecoreUtility.NavigateUrl((Item)Container.DataItem)%>" class="newsHeadline">
<span> <sc:Date ID="Date1" Item="<%# Container.DataItem %>" Field="Posted-Date" Format="MM.dd.yyyy" runat="server" />
<sc:Text ID="Text1" Item="<%# Container.DataItem %>" Field="Title" runat="server" />
</span>
</a>
<!-- <p class="newsSummary">
<asp:Literal ID="litBody" runat="server" Text="<%# SitecoreUtility.TruncateByWords(((Item)Container.DataItem).Fields[Constants.Fields.BODY].Value, 20) %>"></asp:Literal>
...
+ More</p> -->
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Panel ID="pnlPagination" runat="server"></asp:Panel>
<asp:Panel ID="pnlArchive" runat="server">
<!-- <div class="newsArchiveLink">
View Archived News
</div> -->
</asp:Panel>
<asp:Panel ID="pnlCurrent" runat="server">
<div class="newsArchiveLink">
View Current News
</div>
</asp:Panel>
For the ASCX.CS File:
public partial class Homepage_NewsListing : BaseSublayout
{
int CurrentPage = 1;
int PageSize = Constants.Values.SEARCH_SMALL_LIST;
protected void Page_Load(object sender, EventArgs e)
{
CurrentPage = int.Parse(WebUtil.GetQueryString("page", "1"));
List<Item> newsListings = new List<Item>();
Item newsItems = SitecoreUtility.Db.GetItem(Constants.Items.NEWS);
if (WebUtil.GetQueryString("type", "") == "archive")
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) <= DateTime.Now)
&&
(!string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
pnlArchive.Visible = false;
//pnlCurrent.Visible = true;
pnlCurrent.Visible = false;
}
else
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) > DateTime.Now)
||
(string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
//pnlArchive.Visible = true;
pnlArchive.Visible = false;
pnlCurrent.Visible = false;
}
newsContainer.DataSource = DisplayResults(newsListings.OrderByDescending(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList());
newsContainer.DataBind();
}
protected List<Item> DisplayResults(List<Item> results)
{
pnlPagination.Controls.Add(new Pager(results.Count, PageSize, CurrentPage).BuildPaging());
if (CurrentPage > 1)
return results.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();
return results.Take(PageSize).ToList();
}
}
I would first try to make your code a bit more simple (for debugging) and use a fast query to pull items within a date range.
var date = DateTime.Now.AddMonths(3);
var dateString = date.Year.ToString() + date.Month.ToString().PadLeft(2, '0') + date.Day.ToString().PadLeft(2, '0');
var newsList = Sitecore.Context.Database.SelectItems("fast:/sitecore/content/home/your-path-to-news/*[##templatename='Your template name' and #POSTED_DATE > '" + dateString + "']").ToList();
newsList = newsList.OrderByDescending(n => n.Fields["POSTED_DATE"].Value).Take(2).ToList();
newsContainer.DataSource = newsList;
newsContainer.DataBind();

iTextSharp output to PDF

I've been trying to get this working for a long time now and I was hoping that someone could help me out with this. I am trying to save two ListViews from my ASCX control (incorporated to my ASPX page as follows) to a PDF file. I believe that the problem lies in these two lines of code, as I am getting an 'the document has no pages' error when saving. Any ideas would be greatly appreciated! Thanks in advance...
ListView lv1 = (ListView)TagCloudControl1.FindControl("ListView1");
ListView lv2 = (ListView)TagCloudControl1.FindControl("ListView2");
ASPX page:
<%# Register Src="~/tagcloud.ascx" TagName="TagCloudControl" TagPrefix="TagCloud" %>
...
<TagCloud:TagCloudControl ID="TagCloudControl1" runat="server" />
C#:
private void GeneratePDF(string path, string fileName, bool download, string text) {
var document = new Document();
try{
if (download) {
PdfWriter.GetInstance(document, Response.OutputStream);
} else {
PdfWriter.GetInstance(document, new FileStream(path + fileName, FileMode.Create));
}
StringBuilder strB = new StringBuilder();
document.Open();
if (text.Length.Equals(0)) {
TagCloudControl1.BindTagCloud();
using (StringWriter sWriter = new StringWriter(strB)) {
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) {
//var lv1 = (TagCloudControl)ListView.FindControl("ListView1");
//var lv2 = (TagCloudControl)ListView.FindControl("ListView2");
ListView lv1 = (ListView)TagCloudControl1.FindControl("ListView1");
ListView lv2 = (ListView)TagCloudControl1.FindControl("ListView2");
lv1.RenderControl(htWriter);
lv2.RenderControl(htWriter);
}
}
} else {
strB.Append(text);
}
using (TextReader sReader = new StringReader(strB.ToString())) {
List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
foreach (IElement elm in list) {
document.Add(elm);
}
}
} catch (Exception ee) {
ee.ToString();
} finally {
document.Close();
}
}
protected void GeneratePDFAndDownload (object sender, EventArgs e) {
string fileName = "RetroCloud_" + proj_name + "_" + DateTime.Now.Ticks + ".pdf";
GeneratePDF("", fileName, true, "");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
ASCX Control:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="tagcloud.ascx.cs" Inherits="tagcloud" %>
<div style="padding-left: 25px; padding-right: 25px; text-align: center;">
<asp:listview runat="server" ID="ListView1" ItemPlaceholderID="itemPlaceHolder">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Tag") %>
</ItemTemplate>
<EmptyDataTemplate>
<asp:Label ID="negative_tags" runat="server" style="color: #ff0000;" Text="[NO NEGATIVE TAGS FOUND]"></asp:Label>
</EmptyDataTemplate>
</asp:listview>
</div>
<br />
<div style="padding-left: 25px; padding-right: 25px; text-align: center;">
<asp:listview runat="server" ID="ListView2" ItemPlaceholderID="itemPlaceHolder">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Tag") %>
</ItemTemplate>
<EmptyDataTemplate>
<asp:Label ID="positive_tags" runat="server" style="color: #33cc00;" Text="[NO POSITIVE TAGS FOUND]"></asp:Label>
</EmptyDataTemplate>
</asp:listview>
</div>
ASCX CS FILE:
string proj_id, proj_name, iteration;
protected void Page_Load(object sender, EventArgs e)
{
proj_name = Request.QueryString["project"].ToString();
proj_id = Request.QueryString["id"].ToString();
if (String.IsNullOrEmpty((string)Session["iteration"]))
iteration = "0";
else
iteration = (string)Session["iteration"];
BindTagCloud();
}
private void BindTagCloud()
{
int pro_id = Convert.ToInt32(proj_id);
int iteration_id = Convert.ToInt32(iteration);
....
if (iteration_id != 0)
{
ListView1.DataSource = tagCloudNegativeIteration;
ListView1.DataBind();
ListView2.DataSource = tagCloudPositiveIteration;
ListView2.DataBind();
}
else
{
ListView1.DataSource = tagCloudNegative;
ListView1.DataBind();
ListView2.DataSource = tagCloudPositive;
ListView2.DataBind();
}
"The Document has no pages" means you haven't actually written anything to the Document before calling document.close().
I suspect that if you set a breakpoint at the line where you call document.add(), you'll never hit it.
I suggest you take a long, hard look at the input and output to HTMLWorker.ParseToList(). I doubt it's what you expect.

Categories

Resources