ASP.NET HTML Editor - asp.net

I have some problems with adding Html Editor to asp.net web forms.In admin panel,I want to add Html Editor to my text area in order to make a cool User Interface.I have .aspx such as:
<%# Page Title="" Language="C#" MasterPageFile="~/admin/IncubatorAdmin.master"
AutoEventWireup="true" CodeFile="AddFAQ.aspx.cs" Inherits="admin_AddFAQ" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<section id="main" class="column">
<article class="module width_full">
<header><h3>Post FAQ </h3></header>
<div class="module_content">
<fieldset style="width: 60%; float: left; margin-right: 3%;">
<label>Content</label>
<asp:TextBox ID="txtContent" TextMode="MultiLine" Columns="50" Rows="20" runat="server"/>
</fieldset>
<asp:Label ID="ResultLabel" runat="server" Text=""></asp:Label>
<div class="clear"></div>
</div>
<footer>
<div class="submit_link">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Publish FAQ" class="alt_btn" />
</div>
</footer>
</article><!-- end of post new article -->
</section>
and C# code :
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class admin_AddFAQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.select_faq, cn);
command.CommandType = CommandType.StoredProcedure;
int fid = 1;
command.Parameters.AddWithValue("fid", fid);
command.Parameters["fid"].Direction = ParameterDirection.Input;
cn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtContent.Text = (String)reader[1];
}
reader.Close();
cn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.update_faq, cn);
command.CommandType = CommandType.StoredProcedure;
int fid = 1;
command.Parameters.AddWithValue("fid", fid);
command.Parameters["fid"].Direction = ParameterDirection.Input;
command.Parameters.AddWithValue("fcontent", txtContent.Text);
command.Parameters["fcontent"].Direction = ParameterDirection.Input;
cn.Open();
if (command.ExecuteNonQuery() > 0)
{
ResultLabel.Text = "";
ResultLabel.Text = "FAQ page successfully updated";
}
cn.Close();
}
}
}
What changes should I do on .aspx, c# and web.config?Please help me...

You can use ajax control toolkit HTMLEditorExtender
Try http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HtmlEditorExtender/HTMLEditorExtender.aspx

Related

Allow sending email to multiple recipients in ASP.NET with loop and database

I am using ASP.NET and SQL Server to send email to multiple recipients with loop. But there is an error here. I have find my solution from internet but still can't solve it.
Here is the error shown:
var toAddress = mm.To.Add(email);
Here is my .aspx file code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="push_notification_admin.aspx.cs" Inherits="Assignment.push_notification_admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertme() {
Swal.fire(
"The Email Successfully Sent!" ,
'success'
)
}
</script>
<style>
.error {
color: red;
background-image: url("../images/error.png");
background-repeat: no-repeat;
padding-left: 20px;
font-size: 12px;
}
.auto-style1 {
height: 33px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Push Notification:</h2>
<div>
<table style="width: 100%;">
<tr>
<td> <asp:Label ID="Label2" runat="server" Text="Subject"></asp:Label></td>
<td> <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter subjuct!" ControlToValidate="TextBox1" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style1"><asp:Label ID="Label1" runat="server" Text="Content"></asp:Label></td>
<td class="auto-style1"><asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter content!" ControlToValidate="TextBox2" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Here is my aspx.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"]);
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = mm.To.Add(email);
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}
I will be appreciate if someone could help me to solve this problem.
Add method of mm.To is void. i.e. the method returns nothing and hence you cannot assign it to a variable. so your code should be just mm.To.Add(email);. This should fix the error you see.
Here is the latest coding and I have solve it!
The coding that I change to fix it are:
emailArray.Add(reader["Notice_email"].ToString());
and
var toAddress = email;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"].ToString());
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = email;
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}

Call method values on page behind

i have this method in mail.cs file which take one parameter,call store procedures and and return values from database.
public void select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
}
}
}
i want to call the return values from this method on page behind and bind it with label. please advice how to do it.
on my page behind on page load i have done like this
mail callmail = new mail()
now i label1.text how to assign return value to label1.text.
method returns 5 column and i have 5 label on my page so each column will assign to each label.
As per the discussion and assumptions I made following code
mail.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace tempApp4
{
public class mail
{
public DataTable select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}
}
}
}
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server" />
<asp:Label ID="label2" runat="server" />
<asp:Label ID="label3" runat="server" />
<asp:Label ID="label4" runat="server" />
<asp:Label ID="label5" runat="server" />
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
mail mail = new mail();
var table = mail.select("TYPE_VALUE");
label1.Text = Convert.ToString(table.Rows[0][0]);
label2.Text = Convert.ToString(table.Rows[0][1]);
label3.Text = Convert.ToString(table.Rows[0][2]);
label4.Text = Convert.ToString(table.Rows[0][3]);
label5.Text = Convert.ToString(table.Rows[0][4]);
}
}
}
SqlDataAdapter "adapter" used to fetch records from the DB and fill it in dataSet. Data set holds many table as your procedure returns single table the "select" method returns single table at the end as:
return dataSet.Tables[0];
Thus "select" method have return type as "DataTable". Then finally access returned value in code behind using mail class's object and filling the labels by accessing the column as follows:
label1.Text = Convert.ToString(table.Rows[0][0]);
The first 0 in "table.Rows[0][0]" is for rows and second is for column. For column optionally you can specify name of the column as:
label1.Text = Convert.ToString(table.Rows[0]["COLUMN_NAME"]);
Since I don't know the column names I am using indexing.
Hope it helps

How to save and retrieve image from database in ASP.NET

I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("#userid", 222); //image id
//cmd.Parameters.AddWithValue("#pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("#userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
Can anybody help me please?
Thanks in advance...
my code for file upload
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 0px;
}
.auto-style2 {
margin-left: 6px;
margin-top: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto- style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
file upload cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
string path;
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+ FileUpload1.FileName.ToString());
path = "Images/"+FileUpload1.FileName.ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
}
for showing the file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<img src="<%#Eval("image_path") %>" height="100" width="100" />
<td><%#Eval("title") %></td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
file show cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class ShowImage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Images";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
con.Close();
}
}
}
please create a table before proceeding
create table Images(image_path varchar(MAX), title varchar(50));
and lastly add a folder Images in your project by right clicking at your project name

Button OnClick event not working in ASP.NET Web Form Application

I followed this tutorial to create following ASP.NET web form to send parameters to a stored procedure and show the results using Microsoft Report.
this is Incomplete_Prodcut.aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Incomplete_Prodcut.aspx.cs" Inherits="albaraka.Report.Incomplete_Prodcut" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 1116px">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<br />
Type:
<asp:TextBox ID="type" runat="server" Width="64px"></asp:TextBox>
Category:
<asp:TextBox ID="category" runat="server" Width="78px"></asp:TextBox>
Country:
<asp:TextBox ID="country" runat="server" Width="85px"></asp:TextBox>
Subsidary:
<asp:TextBox ID="subsidary" runat="server" Width="72px"></asp:TextBox>
Date:
<asp:TextBox ID="date" runat="server" Width="100px"></asp:TextBox>
<asp:Button ID="btnShow" runat="server" Text="Button" Width="56px" />
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Height="397px" Width="951px" style="margin-top: 17px; margin-right: 0px;"></rsweb:ReportViewer>
</div>
</form>
</body>
</html>
this is Incomplete_Prodcut.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnShow_Click(object Sender, EventArgs e)
{
ShowReport();
}
private void ShowReport()
{
//Reset
ReportViewer1.Reset();
//DataSource
ALBARAKA_Incomplete_Product_DataSet dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, DateTime.Parse(date.Text));
ReportDataSource rds = new ReportDataSource("Incomplete_Product_DataSet", dt);
ReportViewer1.LocalReport.DataSources.Add(rds);
//Path
ReportViewer1.LocalReport.ReportPath = "~/Report/Incomplete_Product.rdlc";
//Paramaeters
ReportParameter[] rptParams = new ReportParameter[] {
new ReportParameter("type",type.Text),
new ReportParameter("category", category.Text),
new ReportParameter("country",country.Text),
new ReportParameter("subsidary",subsidary.Text),
new ReportParameter("date",date.Text),
};
ReportViewer1.LocalReport.SetParameters(rptParams);
//Refersh
ReportViewer1.LocalReport.Refresh();
}
private ALBARAKA_Incomplete_Product_DataSet GetData(string type, string category, string country, string subsidary, DateTime? date)
{
ALBARAKA_Incomplete_Product_DataSet dt = new ALBARAKA_Incomplete_Product_DataSet();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AB_ReportEntities"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("FindIncomplete_Products", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = type;
cmd.Parameters.Add("#category", SqlDbType.NVarChar).Value = category;
cmd.Parameters.Add("#country", SqlDbType.NVarChar).Value = country;
cmd.Parameters.Add("#subsidary", SqlDbType.NVarChar).Value = subsidary;
cmd.Parameters.Add("#date", SqlDbType.DateTime).Value = date;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
I inserted debug point inside the OnClick event of above form, but Once run this application in debug mode and click "btnShow" button this application does not point to this debug point. whats wrong with my approach ?
You have not attached the event handler to the button, add one:-
<asp:Button ID="btnShow" runat="server" Text="Button" Width="56px"
OnClick="btnShow_Click" />
Alternatively, you can also attach the event programmatically like this:-
protected void Page_Load(object sender, EventArgs e)
{
btnShow.Click += btnShow_Click;
}

iTextSharp - corrupt PDF and document close error

This is very close to working. Not sure why I am getting an error at document.Close() or why I am getting a corrupt pdf when I delete document.Close().
It seems to not be posting any info to the pdf.
The code:
Main page with the button the user clicks:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="EventList.ascx.cs"
Inherits="Objects_EventList" %>
<asp:ListView runat="server" ID="lstvwEvents"
OnItemDataBound="lstvwEvents_OnItemDataBound">
<LayoutTemplate>
<asp:ImageButton BorderStyle="0" CssClass="submitbutton" runat="server" AlternateText="Get PDF" ID="LinkButton1" OnClick="btnGenerateReport" />
<div class="eventtease" style="width: 249px;border-bottom: 1px solid #c0c06b;padding-right: 10px;padding-top: 10px;height: 300px;overflow: auto;">
<asp:Literal runat="server" ID="itemPlaceholder" />
<div style="clear: both;"></div>
</div>
</LayoutTemplate>
<ItemTemplate>
<h3 style="clear: both;border-top: 1px solid #c0c06b;padding-top: 10px;"><asp:Literal runat="server" ID="ltrlShortDate" /><br /><%# Eval("EventName").ToString().ToUpper() %><br />(<asp:Literal runat="server" ID="ltrlTimes" />)</h3>
<p class="eventdescription" style="font: normal normal normal 7.5pt/normal Arial, Sans-Serif;margin-top: 3px;">
<%# Eval("Description") %>
</p>
<asp:HyperLink runat="server" ID="lnkLearnMore" Text="LEARN MORE" CssClass="learnmore" Visible="false" />
</ItemTemplate>
Here is the code behind:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
public partial class Objects_EventList : System.Web.UI.UserControl
{
public string city;
public int showcount;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Events();
};
}
protected void Load_Events()
{
EventsDataContext edc = new EventsDataContext();
var events = (from e in edc.tblEvents_Cafes
where e.EventDateTime >= DateTime.Now && e.VenueCity.Trim() == city.Trim() && (e.VenueName.Contains("Café") || e.VenueName.Contains("Cafe") )
orderby e.EventDateTime
select new
{
EventName = e.EventName,
EventDate = e.EventDate,
EventTime = e.EventTime,
Description = edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower()).Select(d => d.Description).First(), // edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower() || d.Keywords.ToLower().CompareTo(e.EventName.ToLower()) >= 0).Select(d => d.Description).First()
}).Take(showcount);
lstvwEvents.DataSource = events;
lstvwEvents.DataBind();
}
protected void lstvwEvents_OnItemDataBound(Object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var tempevent = dataItem.DataItem;
Type t = tempevent.GetType();
DateTime tempdate;
if (DateTime.TryParse((t.GetProperty("EventDate").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlShortDate = new Literal();
ltrlShortDate = (Literal)e.Item.FindControl("ltrlShortDate");
ltrlShortDate.Text = tempdate.ToString("MM/dd/yyyy");
}
if (DateTime.TryParse((t.GetProperty("EventTime").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlTimes = new Literal();
ltrlTimes = (Literal)e.Item.FindControl("ltrlTimes");
ltrlTimes.Text = tempdate.ToString("hh:mm tt");
}
}
}
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)) {
lstvwEvents.DataBind();
using (StringWriter sWriter = new StringWriter(strB)) {
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) {
ListView lv1 = lstvwEvents;
lv1.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 btnGenerateReport(object sender, EventArgs e)
{
string fileName = "Calendar.pdf";
GeneratePDF("", fileName, true, "");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
}

Resources