C# Sending GridViews/DataTables via Email - email

I'm trying the find the best way to send a GridView or DataTable in an email.
Page Behind Code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable s1 = Sql.specificReportData(Convert.ToInt32(Session["userID"]));
this.gv.DataSource = s1.DefaultView;
this.gv.DataBind();
}
This generates and binds the data successfully, but if I try and add the contents of gv to a HTML encoded email then the gv part of the email is blank. Do I need to alter the GridView so it's HTML compliant? I can't find an example of how to do this. Any help appreciated.
edit: Gave answer to Solairaya as he gave fuller example, as well as object flushing and disposal. Marked both answers up as they both helped

Page behind code
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = getHTML(GridView1);
}
private string getHTML(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter textwriter = new StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
gv.RenderControl(htmlwriter);
htmlwriter.Flush();
textwriter.Flush();
htmlwriter.Dispose();
textwriter.Dispose();
return sb.ToString();
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
Page code
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT [UserID], [Name], [Email] FROM [WEB_Users] WHERE ([Name] LIKE '%' + #Name + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="%Moha%" Name="Name" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
</form>

Hai alex try this,
Try this (C#):
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
......
}
public override void VerifyRenderingInServerForm(Control control)
{
}

Related

ASP.Net FormAuthentication response.redirect to IIS Virtual Directory

Have a LoginForm and default asp.net with to buttons on default asp.net. My Target is to after sucssefully Login redirect to default.aspx and by button click connect to IIS Virtual directory.
Login is working fine but the Problem is that i get after button click LoginForm again to authenticate.What should i do to be able to be redirected to virtual directory without authenticate again.
MY LoginForm CodeBehind
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string UserName = Login1.UserName;
string Password = Login1.Password;
bool RememberMe = Login1.RememberMeSet;
string adPath = ConfigurationManager.ConnectionStrings["AD"].ConnectionString;
string DomainFQDN = ConfigurationManager.AppSettings["DomainFQDN"];
string PermitedLoginGroup = ConfigurationManager.AppSettings["PermitiedLoginGroup"];
string DomainNetBiosName = ConfigurationManager.AppSettings["DomainNetBiosName"];
try
{
LdapAuthentication adAuth = new LdapAuthentication(adPath);
if (true == adAuth.Authenticate(UserName, Password, DomainNetBiosName))
{
Session["UserName"] = UserName;
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, UserName, DateTime.Now,
DateTime.Now.AddMinutes(30), Login1.RememberMeSet, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
string ckName = ck.Name;
if (Login1.RememberMeSet)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "Default2.aspx";
FormsAuthentication.RedirectFromLoginPage(UserName, RememberMe);
Response.Redirect(strRedirect, true);
}
}
catch (Exception ex)
{
}
}
Default2.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default2.aspx.cs" Inherits="LoginForm.Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:Button ID="ButtonProd" runat="server" OnClick="ButtonProd_Click" Text="Prod" />
<asp:Button ID="ButtonTest" runat="server" OnClick="ButtonTest_Click" Text="Test" />
</asp:Content>
I am trying to do somthing like this in button click method but i am redirecting again to LoginForm and if i give my credentials again i am able to access Virtual Directory on IIS
protected void ButtonTest_Click(object sender, EventArgs e)
{
HttpCookie ck = (Request.Cookies[".ASPXAUTH"]);
Response.Cookies.Add(ck);
Response.Redirect("Response.Redirect("http://webserver.ad.com/VirtualDirectory",false);
}
Could someone give me some tips...Thanks in advance....

How to send email with attachment xamarin forms

C#:
private void SendEmail(object sender, EventArgs e)
{
string subject = "subject here ";
string body = "body here ";
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("veezo2007pk#gmail.com");
mail.To.Add("veezo2009pk#gmail.com");
mail.Subject = subject;
mail.Body = body;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment();
mail.Attachments.Add(attachment);
smtpServer.Credentials = new NetworkCredential("veezo2007pk", "password");
smtpServer.UseDefaultCredentials = false;
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
private async void File(object sender, EventArgs e)
{
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
fileLabel.Text = filepath;
}
}
XAML:
<Entry Placeholder="Phone No" x:Name="Phone" />
<Button Text="Pick a file" x:Name="fileButton" Clicked="File"/>
<Label Text="This is FileName" x:Name="fileLabel"/>
<Button Text="Submit" Clicked="SendEmail" BackgroundColor="Crimson" TextColor="White" WidthRequest="100" />
I want to send an email with an attachment. If I remove the code for the attachment the email gets to the recipient. When I am using the code for the attachment the email is not sent. I don't know why....
It fails because at no point do you add a file to the attachment variable:
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment();
mail.Attachments.Add(attachment);
You need to add a file path to the parameters of the new System.Net.Mail.Attachment constructor:
attachment = new System.Net.Mail.Attachment("enter file path here");
However, there are other options as well. See this Microsoft documentation.
You can enter a Stream instead of a string (the file path).
I think the following might work for you:
attachment = new System.Net.Mail.Attachment(fileLabel.Text);

Vertx : Post data from html to Java

I tried to send HTML form data to a Java Vertx Verticle but I get null as value.
Here is my code:
public void start(Future<Void> startFuture) throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
Route route = router.route(HttpMethod.POST, "/crypt/testForm/");
route.handler(routingContext -> {
String productType = routingContext.request().getParam("test");
System.out.println(productType);
});
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8085, "localhost", res -> {
if (res.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(res.cause());
}
});
}
And for my html file:
<form action="/crypt/testForm" method="post">
<input type ="text" id="test" name ="test"/>
<input type="submit"/>
</form>
Regards.
Here is my solution, maybe it help,
public void start() throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
router.route("/crypt/test").handler(BodyHandler.create());
router.post("/crypt/test").handler(ctx -> {
ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
JsonArray js = new JsonArray();
js.add(1);
js.add(5);
js.add(3);
ctx.response().end(js.toString());
});
vertx.createHttpServer().requestHandler(router::accept).listen(8085);
}

Entity Framework CheckboxList Database Insert

UPDATED:
I'm using a Detailsview Insert Control and I am trying to create a new row in the database from a checkbox in a CheckBoxList. I'm getting the "The INSERT statement conflicted with the FOREIGN KEY constraint"
Here is my cs:
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffTitle = (CheckBoxList)FindControl("PrincipleStaffTitle");
if (PrincipleStaffTitle != null)
{
foreach (ListItem item in PrincipleStaffTitle.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = Int32.Parse(stringSession);
var ID = item.Value;
using (var context = new FactoryTheaterModelFirstContainer())
{
PrincipleStaff principlestaff = new PrincipleStaff();
principlestaff.PrincipleStaffTitle = ID;
principlestaff.Production_proProductionID = intProductionID;
context.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
}
}
here is the aspx:
<asp:EntityDataSource ID="PrincipleStaffSource" runat="server" ConnectionString="name=FactoryTheaterModelFirstContainer" DefaultContainerName="FactoryTheaterModelFirstContainer" EnableFlattening="False" EntitySetName="PrincipleStaffs" EntityTypeFilter="PrincipleStaff" EnableInsert="True"></asp:EntityDataSource>
<asp:DetailsView ID="AddPrincipleStaffDetailsView" runat="server" AutoGenerateRows="False" DataKeyNames="PrincipleStaffID" DataSourceID="PrincipleStaffSource" Height="50px" Width="730px" DefaultMode="Insert" OnItemInserting="AddPrincipleStaffDetailsView_ItemInserting" OnItemInserted="AddPrincipleStaffDetailsView_ItemInserted">
<Fields>
<asp:TemplateField HeaderText="Add Principle Staff Role:" SortExpression="PrincipleStaffTitle">
<InsertItemTemplate>
<asp:CheckBoxList ID="PrincipleStaffTitle" runat="server" SelectedValue='<%# Bind("PrincipleStaffTitle") %>'>
<asp:ListItem Value="Director">Director(s)</asp:ListItem>
<asp:ListItem Value="Assistant Director">Assistant Director(s)</asp:ListItem>
<asp:ListItem Value="Written By">Written By(s)</asp:ListItem>
<asp:ListItem Value="Executive Producer">Executive Producer(s)</asp:ListItem>
<asp:ListItem Value="Producer">Producer(s)</asp:ListItem>
<asp:ListItem Value="Techincal Director">Technical Director(s)</asp:ListItem>
</asp:CheckBoxList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PrincipleStaffTitle") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
The Production.proProductionID is the foreign key that I'm trying to get into the PrincipleStaff Production_proProductionid column. I can't seem to create the FK relationship.
Thanks for any help that can be provided!
The Below code works. I've since moved my context.savechanges(); outside the loop. My issue was happening on my ItemInserted command.
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffCheckBox = (CheckBoxList)AddPrincipleStaffDetailsView.FindControl("PrincipleStaffTitleCheckBoxList");
if (PrincipleStaffCheckBox.Items.Count > 0)
{
foreach (ListItem item in PrincipleStaffCheckBox.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = 0;
intProductionID = Int32.Parse(stringSession);
var principlestafftitle = item.Value;
try
{
using (var context = new FactoryTheaterModelFirstContainer())
{
Production proid = context.Productions.Single(i => i.proProductionID == intProductionID);
PrincipleStaff principlestaff = new PrincipleStaff()
{
PrincipleStaffTitle = principlestafftitle,
Production_proProductionID = intProductionID
};
proid.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
catch (Exception f)
{
Console.WriteLine(f); // or log to file, etc.
throw; // re-throw the exception if you want it to continue up the stack
}
}
}
}
}

ObjectDatasource passing parameters

I want to Insert data from textboxes using ObjectDatasource. The ObjectDataSource is bound to a gridview but displays certain computed columns only. The Textboxes are used to input all the basic inputs.
ObjectDatasource Delete & Select commands (Link buttons on gridview) are working. However I am having trouble with Insert command. I am not able to figure out how to pass the data from the textboxes as parameters to the ObjectDataSource Insert
EDIT: With the code below, a record is getting inserted. Parameters are getting passed. odssMain.Insert() gives the Error: "Object reference not set to an instance of an object".
EDIT: WHY AM I GETTING THIS ERROR?
Also the ObjectDataSource has been acting weird. After an error, I have to reconfigure the Insert Method again on the ODS Wizard as the method will be blank.
ASP.NET 3.5 & SQL 2008, VS 2008.
Here's my code:
<asp:ObjectDataSource ID="odsMain" runat="server"
SelectMethod="SelectMain" DeleteMethod="DeleteMain"
InsertMethod="InsertMain" UpdateMethod="UpdateMain"
OldValuesParameterFormatString="original_{0}" TypeName="MainDB" >
.......
<InsertParameters>
<asp:Parameter Name="Quantity" Type="Int32" />
</InsertParameters>
DAL FILE:
[DataObjectMethod(DataObjectMethodType.Insert)]
public static int InsertMain(int Quantity)/
{
SqlConnection con = new SqlConnection(GetConnectionString());
string strQuery = "INSERT INTO t_Main (Quantity) VALUES (#Quantity)";
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
CODE BEHIND FILE:
protected void btnSaveAnalysis_Click(object sender, EventArgs e)
{
odsMain.InsertParameters.Clear();
//Store parameters with values to the collection
odsMain.InsertParameters.Add(new Parameter ("Quantity", TypeCode.Int32, iQuantity.ToString()));
//Diferent ways that I tried. Still not working
//odsMain.InsertParameters.Add("Quantity", iQuantity.ToString());
//odsMain.InsertParameters["Quantity"].DefaultValue = iQuantity.ToString();
odsMain.Insert();
}
you could try like this....
ObjectDataSource for InsertParameter looks like below one
<InsertParameters>
<asp:Parameter Name="FirstName" />
<asp:Parameter Name="MiddleName" />
<asp:Parameter Name="LastName" />
<asp:Parameter Name="Desgination" />
<asp:Parameter Name="Address" />
<asp:Parameter Name="City" />
<asp:Parameter Name="State" />
<asp:Parameter Name="Country" />
</InsertParameters>
I will also pass InsertMethod property of ObjectDataSource,which will have an InsertCustomer method.
InsertCustomer method looks like below one :-
public void InsertCustomer(string FirstName, string MiddleName,string LastName, string Desgination, string Address, string City, string State, string Country)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("InsertCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
//this check is necessary, when u don't pass any value as it will pass as [default] and will give error
if (string.IsNullOrEmpty(FirstName))
FirstName = string.Empty;
if (string.IsNullOrEmpty(LastName))
LastName = string.Empty;
if (string.IsNullOrEmpty(MiddleName))
MiddleName = string.Empty;
if (string.IsNullOrEmpty(Desgination))
Desgination = string.Empty;
if (string.IsNullOrEmpty(Address))
Address = string.Empty;
if (string.IsNullOrEmpty(City))
City = string.Empty;
if (string.IsNullOrEmpty(State))
State = string.Empty;
if (string.IsNullOrEmpty(Country))
Country = string.Empty;
cmd.Parameters.AddWithValue("#IV_FirstName", FirstName);
cmd.Parameters.AddWithValue("#IV_LastName", LastName);
cmd.Parameters.AddWithValue("#IV_MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#IV_Desgination", Desgination);
cmd.Parameters.AddWithValue("#IV_Address", Address);
cmd.Parameters.AddWithValue("#IV_City", City);
cmd.Parameters.AddWithValue("#IV_State", State);
cmd.Parameters.AddWithValue("#IV_Country", Country);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Button Save for inserting record.
//Insert record Save Button
protected void btnSave_Click(object sender, EventArgs e)
{
Customer.InsertParameters["FirstName"].DefaultValue = GetGridTextBoxValue("txtFirstName");
Customer.InsertParameters["MiddleName"].DefaultValue = GetGridTextBoxValue("txtMiddleName");
Customer.InsertParameters["LastName"].DefaultValue = GetGridTextBoxValue("txtLastName");
Customer.InsertParameters["Desgination"].DefaultValue= GetGridTextBoxValue("txtDesgination");
Customer.InsertParameters["Address"].DefaultValue = GetGridTextBoxValue("txtAddress");
Customer.InsertParameters["City"].DefaultValue = GetGridTextBoxValue("txtCity");
Customer.InsertParameters["State"].DefaultValue = GetGridTextBoxValue("txtState");
Customer.InsertParameters["Country"].DefaultValue = GetGridTextBoxValue("txtCountry");
Customer.Insert();
}
GetGridTextBoxValue function will get TextBox text value from footer row of respective column.
//Get TextBox value of GridView Footer Row
public string GetGridTextBoxValue(string txtID)
{
try
{
TextBox txt = (TextBox)gvCustomer.FooterRow.FindControl(txtID); // here you can place any text box value on your design page
return txt.Text;
}
catch (Exception ex)
{
return string.Empty;
throw ex;
}
}
and the results image is like this ...