ASP.Net FormAuthentication response.redirect to IIS Virtual Directory - redirect

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....

Related

How use SocialAuth with JSF to redirect?

I'm trying to use SocialAuth, the idea is very simple, click in log in with facebook then redirect the user to my website signed in.
The log in part I get it, which is below :
1) /index.xhtml
<h:form id="login-facebook">
<h:commandButton id="login" action="#{socialFacebook.login}" value="Login"/>
</h:form>
2) socialFacebook bean
package controller;
#ManagedBean(name="socialFacebook")
#RequestScoped
public class SocialFacebook implements Serializable{
private static final long serialVersionUID = -4787254243136316495L;
private String code;
#PostConstruct
public void init(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
System.out.println(p.getFullName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void login(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
//String successUrl = "http://localhost:8080/cc/pages/system/login_facebook.xhtml" + ";jsessionid=" + req.getSession().getId();
String successUrl = "http://localhost:8080/cc/pages/system/index.xhtml" + ";jsessionid=" + request.getSession().getId();
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("authManager", manager);
//redirect to the successful login page
FacesContext.getCurrentInstance().responseComplete();
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
3) Facebook returned the following URL:
http://localhost:8080/cc/pages/system/home_facebook.xhtml;jsessionid=e143aa975fa3f313c677fbcb03e3?code=AQAmJXdQX0B__zJHXnRyPfgaG1CfNUEEEEEEEEEEEEEEEZJLEpsT5s1spd3KtWGWI2HYaIOZKLkrn8axKs4iKwJVQJwJQB_WSs2iWkp2DDDDDDDDDDDDtdRPLPG7psp6r2PYmn7CTm2QNNha7f1QlgmoZtBsIEF0SSSSSSSSSSSSSSSSSSSSSSS8RutAU8dqI2KDE57f#_=_
4) It pass by my init method as BalusC suggest but always prints nope :( :
#ManagedBean(name="redirectFacebook")
#RequestScoped
public class RedirectFacebook implements Serializable{
private static final long serialVersionUID = -566276017320074630L;
private String code;
private Profile profile;
#PostConstruct
public void init(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = (HttpSession) request.getAttribute("jsessionid");
if (request.getAttribute("code") != null)
System.out.println("code");
else
System.out.println("nope :(");
if (session != null){
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
profile = provider.getUserProfile();
System.out.println(profile.getFullName());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5) And it prints nope :( too in my home_facebook page:
<h:form id="redirect-facebook-form">
<f:metadata>
<f:viewParam name="code" value="#{redirectFacebook.code}" />
</f:metadata>
<h:panelGroup rendered="#{not empty redirectFacebook.profile}">
Hello, you're successfully associated as #{socialFacebook.profile.firstName} on Facebook
</h:panelGroup>
<h:panelGroup rendered="#{empty redirectFacebook.profile}">
Nope :(
</h:panelGroup>
</h:form>
But, I'm a bit confuse how to get the result in my bean and do some verifications as if the user is registered or not for instance. I know, looking some code in Google, that I have to do this, but how can I redirect to my bean and do this and redirect the user to the proper page ?
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p;
p = provider.getUserProfile();
This is really taking some nights to figure it out.
Any idea is very appreaciated, thanks.
I don't see any code level issue except you are using localhost in URL.
Here is a wiki link which describes how to run application with localhost.
Please let me know if this does not work.

Redirecto to another page with a filled form in JSF?

I'm trying to do a 'login with facebook' button, which works ok, but I would like to redirect to another page with the user data filled in a form.
SocialFacebook Controller
public void login(){
try {
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://localhost:8080/cc/pages/system/register.xhtml";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.setAttribute("authManager", manager);
//after check out in facebook, redirect to the proper page
logged();
//redirect to the successful login page
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So when the user hit the button, 'log in with facebook' in my index.xhtml:
<h:body>
<h:form id="login-facebook">
<h:commandButton id="login" action="#{socialFacebook.login}" value="Login"/>
</h:form>
</h:body>
It redirects to register.xhtml page with the URL like this:
http://localhost:8080/cc/pages/system/register.xhtml?code=AQC_3oCPjlyvZ51dpzxVdBNS1JfgwwZluBSduU7FG01esgVQT6Qxq8gWYRUsGz64aXDvXB1195m0CHZGmdvsmjLxtmbuUSSSqH7i49pcb6g9Begt4Yol1rqWFQGGGGGGGGGGGJ9mlWiEq4Aknlh1J2su2a9l0GzyLB21J4BgNgfBw3DUtwn-RkT00E7BsFpISiXKE7EVsT5NgxPBtOWIUY#_=_
The thing is now, I would like to get this code in my bean and do the checking and fill the form in register.xhtml
So I create this method at the same bean :
private void logged(){
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
try {
// get the auth provider manager from session
if (manager != null){
// call connect method of manager which returns the provider object.
// Pass request parameter map while calling connect method.
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
session.setAttribute("profile", p);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But it I'm not able to get the parameter code from my request.
How can I get this code, do the checking and fill the form after that ?
**
EDIT
SocialFacebook.java
package jpa.control;
// imports..
#ManagedBean(name="socialFacebook")
#RequestScoped
public class SocialFacebook implements Serializable{
private static final long serialVersionUID = -4787254243136316495L;
#ManagedProperty("#{param.code}")
private String code;
public void login(){
try {
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://localhost:8080/cc/pages/system/register.xhtml";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.setAttribute("authManager", manager);
//after check out in facebook, redirect to the proper page
logged();
//redirect to the successful login page
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void logged(){
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
System.out.println("*******************************");
System.out.println(code); // keeps return NULL everytime
System.out.println("*******************************");
try {
// get the auth provider manager from session
if (manager != null){
// call connect method of manager which returns the provider object.
// Pass request parameter map while calling connect method.
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
session.setAttribute("profile", p);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Get's and Set's
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
I solve my problem creating a webfilter which gets the request and responde then I could fill the user date in my url and get then in my form page:
#WebFilter("/facebook/*")
public class LoginFilter implements Filter {
#EJB UserEAO userEAO;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
if (userEAO.find(p.getEmail()) == null){
response.sendRedirect
(
request.getContextPath() +
"/pages/system/register.xhtml?" +
"firstName=" + p.getFirstName()
);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my register page:
<ui:composition template="/resources/jsf/include/default.xhtml">
<ui:define name="title">
</ui:define>
<ui:define name="header">
</ui:define>
<ui:define name="content">
<h:form id="register_form">
<f:metadata>
<f:viewParam name="firstName" value="#{userc.userb.user.firstName}" />
</f:metadata>
Name: <h:message id="m_name" for="name" styleClass="red" />
<h:inputText id="name" value="#{userc.userb.user.firstName}">
<f:validateLength minimum="1" maximum="20" />
<f:ajax event="blur" render="m_name" />
</h:inputText>

Populating ListBox in ASP.NET MVC from SQL CE (C#)

I can't find an example that suits my needs anywhere, so I'm asking you guys.
Im trying to populate a ListBox on my website with content from an SQL CE database.
I used Asp.Net MVC DropDownList Data Binding as an example to create my ListBox.
I have now hit a deadend and could use some help, here is what i got:
Index.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Headline</h2>
<% using (Html.BeginForm())
{ %>
<%= Html.ListBoxFor(x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text"))%>
<br /><input type="submit" value="Show" style="width: 72px" />
<% } %>
</asp:Content>
HomeController.cs
public ActionResult Index()
{
var model = new ItemsViewModel();
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\RSSdb.sdf;Persist Security Info=False"))
{
con.Open();
string cmdString = string.Format("SELECT Name, ID FROM TableIndex WHERE (Active = N'true')");
using (SqlCeCommand cmd = new SqlCeCommand(cmdString, con))
{
using (SqlCeDataReader dataRead = cmd.ExecuteReader())
{
model = new ItemsViewModel
{
Items = new[]
{
new SelectListItem { Value = "Foo", Text = "Foo" } ,
new SelectListItem { Value = "Bar", Text = "Bar" }
}
};
}
}
}
return View(model);
}
ItemsViewModel.cs
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Now what i need is to have the code in HomeController.cs be something like this:
model = new ItemsViewModel
{
Items = new[]
{
While(dataRead.Read())
{
new SelectListItem { Value = dataRead["ID"], Text = dataRead["Name"] };
}
}
};
But this don't work, and i have no idea how else to do it, all help is appreciated.
You've probably realized by now that you can't put a while loop within an array initializer. One approach to solving this would be to create a method which will build the list for you like so:
public IList<SelectListItem> GetSelectListItems()
{
IList<SelectListItem> items = new List<SelectListItem>();
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\RSSdb.sdf;Persist Security Info=False"))
{
con.Open();
string cmdString = "SELECT Name, ID FROM TableIndex WHERE (Active = N'true')";
using (SqlCeCommand cmd = new SqlCeCommand(cmdString, con))
{
using (SqlCeDataReader dataRead = cmd.ExecuteReader())
{
while(dataRead.Read())
{
items.Add(new SelectListItem
{
Value = dataRead["ID"],
Text = dataRead["Name"]
});
}
}
}
}
return items;
}
Then your action could be as simple as:
public ActionResult Index()
{
var model = new ItemsViewModel
{
Items = GetSelectListItems()
};
return View(model);
}

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 ...

C# Sending GridViews/DataTables via 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)
{
}