How to generate Checkboxlist dynamically using ASP.NET Literal - html

I'm trying to generate checkboxlist dynamically using this code:
string IDToEdit = Request.QueryString["id"].ToString();
List<DAL.EF.Dental_Price_Lists> lstOfCategDental = BAL.Helpers.Prices.GetDentalCategories();
string HTMLTag = "";
string HTMLTag2 = "";
int count = 1;
foreach (var x in lstOfCategDental)
{
HTMLTag += string.Format("<a href='#tab{0}'>{1}</a>", count, x.Category);
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
HTMLTag2 += string.Format("<div id='tab{0}' class='tab'>", count);
HTMLTag2 += string.Format(" <asp:CheckBoxList ID='chkListDental{0}' runat='server'>", count);
foreach (var price in priceList)
{
HTMLTag2 += string.Format(" <asp:ListItem Value='{0}' price='{1}' Text='{2}'></asp:ListItem>", price.ID.ToString(), price.Price.ToString(), price.Type);
}
HTMLTag2 += " </asp:CheckBoxList>";
HTMLTag2 += " </div>";
count++;
}
ltrCategories.Text = HTMLTag;
ltrChkListDental.Text = HTMLTag2;
}
but it didn't work correctly "explained in the below image", i think thats because the ASP.NET tag instead of the HTML tag but i'm not sure of that ... so, can you help me solve this issue?
As you see in the following image the asp.net tags didn't converted to html tags?
http://i.stack.imgur.com/ufSq3.png

You can not do it. But you can instantiate a new control and then append it the the page controls property:
foreach (var x in lstOfCategDental) {
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
var checkboxList = new CheckBoxList();
checkboxList.ID = string.Format("chkListDental{0}", count);
foreach (var price in priceList) {
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
Page.Controls.Add(checkboxList);
}
or use the RenderControl method of the control for each of the controls, but it is not recommended.
StringBuilder sb = new StringBuilder();
StringWriter stWriter = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
.
.
.
foreach (var x in lstOfCategDental) {
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
var checkboxList = new CheckBoxList();
checkboxList.ID = string.Format("chkListDental{0}", count);
foreach (var price in priceList) {
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
checkboxList.RenderControl(htmlWriter);
}
ltrChkListDental.Text = sb.ToString();

I solved it by creating the div dynamically too then add the checkboxlist to that div.
string IDToEdit = Request.QueryString["id"].ToString();
List<DAL.EF.Dental_Price_Lists> lstOfCategDental = BAL.Helpers.Prices.GetDentalCategories();
string HTMLTag = "";
int count = 1;
foreach (var x in lstOfCategDental)
{
var checkboxList = new CheckBoxList();
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
HTMLTag += string.Format("<a href='#tab{0}'>{1}</a>", count, x.Category);
checkboxList.ID = string.Format("chkListDental{0}", count);
HtmlGenericControl divControl = new HtmlGenericControl("div");
// Set the properties of the new HtmlGenericControl control.
divControl.ID = "tab" + count;
divControl.Attributes.Add("class", "tab");
// Add the new HtmlGenericControl to the Controls collection of the
// PlaceHolder control.
divPlaceHolder.Controls.Add(divControl);
foreach (var price in priceList)
{
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
divControl.Controls.Add(checkboxList);
}
ltrCategories.Text = HTMLTag;

Related

Export data from the mssql database to a csv file

good work
v.b.net I will start a new project on my project and my purpose in this project from the database to extract data from certain tables and I want to save as csv
"##FILE VERSION##","251" "##TABLEDEF START##"
"MESAJ=String,50,""MESAJ"","""",50,Data,"""""
"ID=Integer,0,""ID"","""",10,Data,"""""
"SUBEIND=Integer,0,""SUBEIND"","""",10,Data,"""""
"KASAIND=Integer,0,""KASAIND"","""",10,Data,""""" "##INDEXDEF START##"
"##INDEXDEF END##" "##TABLEDEF END##"
"MESAJ","ID","SUBEIND","KASAIND", "YeniFirma","112","100","101",
"YeniCari","100","100","101", "YeniStok","101","100","101", –
Send your sql dataset result as a parameter to this function. It create csv format for you.
public string ConvertToCSV(DataSet objDataSet)
{
StringBuilder content = new StringBuilder();
if (objDataSet.Tables.Count >= 1)
{
System.Data.DataTable table = objDataSet.Tables[0];
if (table.Rows.Count > 0)
{
DataRow dr1 = (DataRow)table.Rows[0];
int intColumnCount = dr1.Table.Columns.Count;
int index = 1;
foreach (DataColumn item in dr1.Table.Columns)
{
content.Append(String.Format("\"{0}\"", item.ColumnName));
if (index < intColumnCount)
content.Append(",");
else
content.Append("\r\n");
index++;
}
foreach (DataRow currentRow in table.Rows)
{
string strRow = string.Empty;
for (int y = 0; y <= intColumnCount - 1; y++)
{
strRow += "\"" + currentRow[y].ToString() + "\"";
if (y < intColumnCount - 1 && y >= 0)
strRow += ",";
}
content.Append(strRow + "\r\n");
}
}
}
This function send a mail:
public void sendMail(string csv)
{
var sendMailThread = new Thread(() =>
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv));
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = DateTime.Now.ToShortDateString() + "Report.csv";
MailMessage ePosta = new MailMessage();
ePosta.From = new MailAddress("xx");
ePosta.To.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.Attachments.Add(attachment);
ePosta.Subject = DateTime.Now + " Subject";
ePosta.Body = DateTime.Now + " body message.";
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new System.Net.NetworkCredential("xxx", "xxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
object userState = ePosta;
smtp.SendAsync(ePosta, (object)ePosta);
});
sendMailThread.Start();
}

In SSIS,How to read the data from Object and mail in the form of Table

My main objective is:
To read the object which I get through Execute Sql task
Then Using Script task I want to mail it ,but I need to format the values in object in form of table as the body of mail.
And IF Time TimeDifference Column had value =<100 Then Row should be Green Else Red.
So I have an Object called "ResultSet",I pass to Script Task, I convert it into c# table structure and place it in a variable called "ApplicationTotal".
Below is the code for that which works fine.
public void Main()
{
DataTable dtTotal = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
adapter.Fill(dt, Dts.Variables["InactiveSet"].Value);
// In the first Run dtTotal is created
if (Convert.ToInt32(Dts.Variables["InsertedRowCountTotal"].Value) == 0)
{
foreach (DataColumn dc in dt.Columns)
{
dtTotal.Columns.Add(dc.ColumnName,dc.DataType);
}
}
else // In the next runs dtTotal is retrieved from variable
{
dtTotal = (DataTable)Dts.Variables["InactiveSetTotal"].Value;
}
foreach (DataRow dr in dt.Rows)
{
DataRow newDR = dtTotal.NewRow();
foreach( DataColumn dc in dt.Columns)
{
newDR[dc.ColumnName] = dr[dc.ColumnName];
}
dtTotal.Rows.Add(newDR);
}
Dts.Variables["InactiveSetTotal"].Value = dtTotal;
Dts.Variables["InsertedRowCountTotal"].Value = Convert.ToInt32(Dts.Variables["InsertedRowCountTotal"].Value) + Convert.ToInt32(Dts.Variables["InsertedRowCount"].Value);
Dts.TaskResult = (int)ScriptResults.Success;
}
Then I pass ApplicationTotal object to script task where i have to read the object and mail the details in form of table.I am successful in sending mail but I am not able to format the data in table and change the colour
I get the output in mail as
if (Convert.ToInt32(Dts.Variables["InsertedRowCount"].Value) == 0)
{
return;
}
#region BuildingEmailBody
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("Monitor Application Report"));
sb.AppendLine();
sb.AppendLine();
//sb.AppendLine(string.Format("Following are the Details:\n\n<TABLE><TR>\n<TH>{0}</TH><TH>{1}</TH><TH>{2}</TH> <TH>{3}</TH> <TH>{4}</TH>\n</TR>\n", "TimeDifferences(Minutes) ", "UpdateTime", "ApplicationName", "ServerName", "DatabaseName"));
OleDbDataAdapter adapter = new OleDbDataAdapter();
if (Convert.ToInt32(Dts.Variables["InsertedRowCount"].Value) > 0)
{
sb.AppendLine();
DataTable ApplicationTotal = new DataTable();
ApplicationTotal = (DataTable)Dts.Variables["ApplicationTotal"].Value;
foreach (DataRow dr in ApplicationTotal.Rows)
{
sb.AppendLine(string.Format("{0} {1} {2} {3} {4} ", dr[0], dr[1], dr[2], dr[3], dr[4]));
}
sb.AppendLine();
}
# endregion
In the above code ,
1.I have taken a variable html in which I create table and load the data in the table.
2.I add the color coding to the table's rows based on condition
3.Make IsBodyHtml =true
4.Pass html variable to smpt.Send(message)
public void Main()
{
string html = string.Empty;
if (Convert.ToInt32(Dts.Variables["InsertedRowCount"].Value) == 0)
{
return;
}
#region BuildingEmailBody
OleDbDataAdapter adapter = new OleDbDataAdapter();
if (Convert.ToInt32(Dts.Variables["InsertedRowCount"].Value) > 0)
{
DataTable ApplicationTotal = new DataTable();
ApplicationTotal = (DataTable)Dts.Variables["ApplicationTotal"].Value;
html = "Monitor Application Report <br></br> <style type='text/css'>td.datacellone { background-color: #FF0000; color: black;}td.datacelltwo { background-color: #00FF00; color: black;}</style> <table border=1>";
//add header row
html += "<tr>";
for (int i = 0; i < ApplicationTotal.Columns.Count; i++)
{
html += "<th>" + ApplicationTotal.Columns[i].ColumnName + "</th>";
}
html += "</tr>";
//add rows
for (int i = 0; i < ApplicationTotal.Rows.Count; i++)
{
html += "<tr>";
for (int j = 0; j < ApplicationTotal.Columns.Count; j++)
if (Convert.ToInt32(ApplicationTotal.Rows[i][0].ToString()) > Convert.ToInt32(Dts.Variables["TimeDifference"].Value.ToString()))
html += "<td class='datacellone'>" + ApplicationTotal.Rows[i][j].ToString() + "</td>";
else
html += "<td class='datacelltwo'>" + ApplicationTotal.Rows[i][j].ToString() + "</td>";
html += "</tr>";
}
html += "</table>";
}
//MessageBox.Show(Dts.Variables["TimeDifference"].Value.ToString());
# endregion
#region SendingEmail
string sendTo = Dts.Variables["AlarmOperator"].Value.ToString();
string from = "pemsadmin#pemsportal.com.au";
string subject = "Monitor Application Status";
string server = "192.168.240.171";
string user = "pemsadmin#pemsportal.com.au";
string password = "Sawu7619";
string domain = "pemsportal.com.au";
int port = 25;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, sendTo, subject, html.ToString());
message.IsBodyHtml = true;
message.Body = html.ToString();
System.Net.Mail.SmtpClient smpt = new System.Net.Mail.SmtpClient(server, port);
smpt.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
smpt.Credentials = new System.Net.NetworkCredential(user, password, domain);
smpt.Send(message);
#endregion
Dts.TaskResult = (int)ScriptResults.Success;
}

Export html to Excel format? [duplicate]

I want to extract some data like " email addresses " .. from table which are in PDF file and use this email addresses which I extract to send email to those people.
What I have found so far through searching the web:
I have to convert the PDF file to Excel to read the data easily and use them as I want.
I find some free dll like itextsharp or PDFsharp.
But I didn't find any snippet code help to do this in C#. is there any solution ?
You absolutely do not have to convert PDF to Excel.
First of all, please determine whether your PDF contains textual data, or it is scanned image.
If it contains textual data, then you are right about using "some free dll". I recommend iTextSharp as it is popular and easy to use.
Now the controversial part. If you don't need rock solid solution, it would be easiest to read all PDF to a string and then retrieve emails using regular expression.
Here is example (not perfect) of reading PDF with iTextSharp and extracting emails:
public string PdfToString(string fileName)
{
var sb = new StringBuilder();
var reader = new PdfReader(fileName);
for (int page = 1; page <= reader.NumberOfPages; page++)
{
var strategy = new SimpleTextExtractionStrategy();
string text = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
text = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(text)));
sb.Append(text);
}
reader.Close();
return sb.ToString();
}
//adjust expression as needed
Regex emailRegex = new Regex("Email Address (?<email>.+?) Passport No");
public IEnumerable<string> ExtractEmails(string content)
{
var matches = emailRegex.Matches(content);
foreach (Match m in matches)
{
yield return m.Groups["email"].Value;
}
}
Using bytescout PDF Extractor SDK we can be able to extract the whole page to csv as below.
CSVExtractor extractor = new CSVExtractor();
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";
TableDetector tdetector = new TableDetector();
tdetector.RegistrationKey = "demo";
tdetector.RegistrationName = "demo";
// Load the document
extractor.LoadDocumentFromFile("C:\\sample.pdf");
tdetector.LoadDocumentFromFile("C:\\sample.pdf");
int pageCount = tdetector.GetPageCount();
for (int i = 1; i <= pageCount; i++)
{
int j = 1;
do
{
extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
tdetector.GetPageRect_Top(i),
tdetector.GetPageRect_Width(i),
tdetector.GetPageRect_Height(i)
);
// and finally save the table into CSV file
extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
j++;
} while (tdetector.FindNextTable()); // search next table
}
public void Convert(string fileNames) {
int pageCount = 0;
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNames);
pageCount = reader.NumberOfPages;
string ext = System.IO.Path.GetExtension(fileNames);
//string[] outfiles = new string[pageCount];
//Excel.Application app = new Excel.Application();
//app.Workbooks.Add("");
CSVExtractor extractor = new CSVExtractor();
//string outfilePDF1 = fileNames.Replace((System.IO.Path.GetFileName(fileNames)), (System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_rez" + ".csv"));
string outfilePDFExcel1 = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_rez" + ".xls"));
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";
string folderName = #"C:\Users\Dafina\Desktop\PDF_EditProject\PDF_EditProject\PDFs";
string pathString = System.IO.Path.Combine(folderName, System.IO.Path.GetFileName(fileNames).Replace(".pdf", "")) + "-CSVs";
System.IO.Directory.CreateDirectory(pathString);
for (int i = 0; i < pageCount; i++)
{
string outfilePDF = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_" + (i + 1).ToString()) + ext);
extractor.LoadDocumentFromFile(outfilePDF);
//string outfile = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
// (System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_" + (i + 1).ToString()) + ".csv");
string outfile = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "-CSVs\\" + "Sheet_" + (i + 1).ToString()) + ".csv");
extractor.SaveCSVToFile(outfile);
}
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
Console.WriteLine("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
string[] cvsFiles = Directory.GetFiles(pathString);
Array.Sort(cvsFiles, new AlphanumComparatorFast());
//string[] lista = new string[pageCount];
//for (int t = 0; t < pageCount; t++)
//{
// lista[t] = cvsFiles[t];
//}
//Array.Sort(lista, new AlphanumComparatorFast());
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
for (int i = 0; i < cvsFiles.Length; i++)
{
int sheet = i + 1;
xlWorkSheet = xlWorkBook.Sheets[sheet];
if (i < cvsFiles.Length - 1)
{
xlWorkBook.Worksheets.Add(Type.Missing, xlWorkSheet, Type.Missing, Type.Missing);
}
int sheetRow = 1;
Encoding objEncoding = Encoding.Default;
StreamReader readerd = new StreamReader(File.OpenRead(cvsFiles[i]));
int ColumLength = 0;
while (!readerd.EndOfStream)
{
string line = readerd.ReadLine();
Console.WriteLine(line);
try
{
string[] columns = line.Split((new char[] { '\"' }));
for (int col = 0; col < columns.Length; col++)
{
if (ColumLength < columns.Length)
{
ColumLength = columns.Length;
}
if (col % 2 == 0)
{
}
else if (columns[col] == "")
{
}
else
{
xlWorkSheet.Cells[sheetRow, col + 1] = columns[col].Replace("\"", "");
}
}
sheetRow++;
}
catch (Exception e)
{
string msg = e.Message;
}
}
int k = 1;
for (int s = 1; s <= ColumLength; s++)
{
xlWorkSheet.Columns[k].Delete();
k++;
}
releaseObject(xlWorkSheet);
readerd.Close();
}
xlWorkBook.SaveAs(outfilePDFExcel1, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
var dir = new DirectoryInfo(pathString);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete(true);
}
Probably the Best code would be to use Third party dll
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
string pathToPdf = #"D:\abc\abc.pdf";
string pathToExcel = Path.ChangeExtension(pathToPdf, ".xls");
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
f.ExcelOptions.ConvertNonTabularDataToSpreadsheet = false;
// 'true' = Preserve original page layout.
// 'false' = Place tables before text.
f.ExcelOptions.PreservePageLayout = true;
// The information includes the names for the culture, the writing system,
// the calendar used, the sort order of strings, and formatting for dates and numbers.
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
ci.NumberFormat.NumberDecimalSeparator = ",";
ci.NumberFormat.NumberGroupSeparator = ".";
f.ExcelOptions.CultureInfo = ci;
f.OpenPdf(pathToPdf);
if (f.PageCount > 0)
{
int result = f.ToExcel(pathToExcel);
// Open the resulted Excel workbook.
if (result == 0)
{
System.Diagnostics.Process.Start(pathToExcel);
}
}
}
}
}

max lengt or else dots - How or what should i write?

I want the script to show max 26 letters and if there is more I want it to make (...) <-- so that you can se there is more letters in the link.
First I put a bit of a script I have for another site containing a variable to do that, however it doesn't work in RSS:
{
temp.Add(titel);
count++;
string titel_kort = titel;
if (titel.Length > 26)
{
titel_kort = titel.Substring(0, 26) + "...";
}
}
And this is the script I want to integrate to:
#using System.Xml.XPath;
#using System.Xml;
#{
try
{
XmlTextReader udBrudRSS = new XmlTextReader("http://tidende.dk/rss.aspx");
XmlDocument doc = new XmlDocument();
doc.Load(udBrudRSS);
XmlNodeList rssItems = doc.SelectNodes("//item");
var count = 0;
foreach (XmlNode node in rssItems )
{
count++;
if (count > 3) { break; }
<div class="nyhedlink">- #node["title"].InnerText</div>
}
}
catch {}
}
You could something like this :
using (var webclient = new WebClient())
{
var data = webclient.DownloadData("http://tidende.dk/rss.aspx");
var oReader = new XmlTextReader(new MemoryStream(data));
var xml = XDocument.Load(oReader);
var values = xml.XPathSelectElements("//item").Take(3).Select(p => new
{
Link = p.XPathSelectElement("//link").Value,
Title = (p.XPathSelectElement("./title").Value.Length > 26) ?
p.XPathSelectElement("./title").Value.Substring(0, 26).Trim() + "..." :
p.XPathSelectElement("./title").Value.Trim()
});
foreach (var item in values)
{
<div class="nyhedlink">- #item.Title</div>
}
}
Sometimes is better use WebClient to make the petition instead of XmlTextReader see this question for a good explanation.

RazorScript Count Not Working

I am using DNN and have (with the help of a co-worker) created a script to print out items from the Form and List module, but need to limit the output to three. However, the script returns nothing. Can anyone point to me where I may have gone wrong?
http://jsfiddle.net/VsF6c/
#using System.Data;
#using DotNetNuke.Entities.Modules;
#using DotNetNuke.Entities.Portals;
#using DotNetNuke.Modules.UserDefinedTable;
#using DotNetNuke.Entities.Users;
#{
var mc = new ModuleController();
var tc = new DotNetNuke.Entities.Tabs.TabController();
int portalId = PortalController.GetCurrentPortalSettings().PortalId;
var flModule = mc.GetModuleByDefinition(portalId, "Form and List");
int moduleId = -1;
int tabId = -1;
var tab = tc.GetTabByName("News", portalId);
if (tab != null) {
tabId = tab.TabID;
}
if (flModule != null) {
moduleId = 968;
}
var ds = (new UserDefinedTableController(moduleId, tabId, new UserInfo())).GetDataSet(true);
}
<ul>
#for (int i = 0; i < 3; i++)
{
DataRow row = ds.Tables["Data"].Rows[i];
<li>
<a href='/news##row["UserDefinedRowId"]' title='#row["Title"]'>#row["Title"]</a>
</li>
}
</ul>