connection string manage with DropDownList - asp.net

Suppose we have 5 companies with five database. Now the situation is we need to change the database path[connection string] on company name which is appear in dropdownlist. When we select the company name on selection of dropdown value we need to go to that companies database. How to do this in asp.net and what necessary changes do in web.config and dropdown event of company name.
now i tried:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text.Equals("RVL LOGISTICS (I) PVT LTD"))
{
string cs = ConfigurationManager.ConnectionStrings["CompMasterConnectionString"].ConnectionString;
}
else if (DropDownList1.SelectedItem.Text.Equals("SIMONS SHIPPING PVT LTD"))
{
string vs = ConfigurationManager.ConnectionStrings["DUM01ConnectionString"].ConnectionString;
}
else
{
DropDownList2.Enabled = false;
}
}

PLease find below code to change the connection string dynamiccaly at runtime based on dropdown list selected text or value as per your need.
<asp:DropDownList ID="ddltest" AutoPostBack="True" OnSelectedIndexChanged="ddltest_OnSelectedIndexChanged" runat="server">
<asp:ListItem Text="CompanyName" Value="1"></asp:ListItem>
<asp:ListItem Text="CompanyName1" Value="2"></asp:ListItem>
</asp:DropDownList>
protected void ddltest_OnSelectedIndexChanged(object sender, EventArgs e)
{
var conString = "";
var ConStringName = "test";
switch (ddltest.SelectedItem.Text.ToLower())
{
case "CompanyName":
conString = GetConStringFromAppSetting("CompanyName");
AddUpdateConnectionString(conString, ConStringName);
break;
case "CompanyName1":
conString = GetConStringFromAppSetting("CompanyName1");
AddUpdateConnectionString(conString, ConStringName);
break;
}
}
private string GetConStringFromAppSetting(string test)
{
var constring = ConfigurationManager.AppSettings[test].Trim();
return constring;
}
private void AddUpdateConnectionString(string conStringValue, string conStringName)
{
var path = Server.MapPath("~/Web.Config");
var doc = new XmlDocument();
doc.Load(path);
if (doc.DocumentElement != null)
{
var list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[#name='{0}']", conStringName));
if (list != null)
{
var node = list[0];
if (node.Attributes != null) node.Attributes["connectionString"].Value = conStringValue;
}
}
doc.Save(path);
}
in Above code i changed your if else block to switch block, which helps to read code nicely. It will check the selected text value from the dropdown.
First Method is GetConStringFromAppSetting. It will accept the selected Text of dropdown and it will check the same in AppSetting Section of WebConfig and get the value from that.
In the AppSetting of Web Config do work like below:
<appSettings>
<add key="CompanyName" value="constringOfThatCompany" />
<add key="CompanyName1" value="constringOfThatCompany1" />
</appSettings>
After that there is method is AddUpdateConnectionString. IT will accept the Constring value which is recevied from from above method and default connection string name.
After that in that method:
Load the config file.
Load that file in XMLDOcument so we can parse easily.
3.Find the connection string node by name we have parsed.
Set the value of that node that connection string value.
Save the document (web.COnfig) Again.
Note: It is not the good way to change the web config like this. one can provide other secure way.

Related

Posting data between Asp.Net Web Pages

I have a list of strings, which are generated on a imagebutton_click method. I want to be able to use this list in another webpage.
How ever im not quite sure how to go about posting it between the two pages.
I have the following code below:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
RadGrid rg = RadGrid1;
//Get selected rows
GridItemCollection gdc = (GridItemCollection)rg.SelectedItems;
foreach (GridItem gi in gdc)
{
if (gi is GridDataItem)
{
GridDataItem gdi = (GridDataItem)gi;
if (!string.IsNullOrEmpty(gdi["Email"].Text))
{
string client = gdi["Email"].Text;
//Creating a List of Clients to be Emailed
emailList.Add(email);
}
}
//Enable the Prepare Email Page
PageView2.Selected = true;
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (emailList.Count != 0)
{
for (int i = 0; i < emailList.Count; i++)
{
_to = emailList[i].ToString() + ";";
}
}
else
{
_to = emailList[1].ToString();
}
//Processing Client Email
string _from = sec.GetCurrentUserEmail("test");
string _cc = "";
string _subject = SubjectTB.Text;
string _body = EmailEditor.Content;
string _tempTo = sec.GetCurrentUserEmail("temp");
string _msg = sec.SendMail(_tempTo, _cc, _from, _subject, _body, "");
if (_msg == "success")
{
//Thank the user and record mail was delivered sucessfully
TestPanel.Visible = true;
}
}
How do I get the values of emailList to be passed through to ImageButton2_click(object sender, ImageClickEventArgs e). Currently it just passes through a null value. I gather I need to use HTML forms to do the request. Thanks.
I'm guessing that emailList is a private variable? Wouldn't you be able to add that to the LoadControlState and SaveControlState so that it'll be available for ImageButton2_Click later?
Here is an example: http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadcontrolstate%28v=vs.80%29.aspx
Another possibility is hidden field, that might be the simplist way, but not as secure.
You can get a good idea about state management in ASP.Net here. For your case if button1 and button2 are in the same aspx page, Viewstate would be a good idea. If they are in diferent pages then use Session state management.

Using session for user authentication in asp.net c#

I am using session to authenticate a user. I have 2 web pages in my project. One is webform and other one is EntryForm.aspx and other one is log.aspx
In log.aspx i have done
protected void Button1_Click(object sender, EventArgs e)
{
user_login loginu = new user_login();
String uid_db = loginu.login(this.DropDownList1, this.TextBox1, this.TextBox2, this.Label5);
if (uid_db == "invalid")
{
Label5.Visible = true;
Label5.Text = "Invalid Login";
}
else
{
string uname = uid_db.Substring(0, uid_db.IndexOf(",")).Trim();
string[] tokens = uid_db.Split(',');
string dbname = tokens[tokens.Length - 1];
Session["login"] = uname;
Session["db"] = dbname;
Response.Redirect("EntryForm.aspx");
}
}
In class user_login I am taking the password stored in the database and matching it with the value entered by user. if it finds a value i redirect it to EntryForm.aspx. In which i check for session variable as follows
protected void Page_Load(object sender, EventArgs e)
{// CHEK SESSION VARIABLE AND LOAD dropdownlist1 WITH VALUES
if (!IsPostBack)
{
String DB = "";
String AccountID = "";
if (Session["login"] != null && Session["db"] != null)
{
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
}
else
{
Response.Redirect("log.aspx");
}
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
}
This is what i have done do authenticate a user. On server i have done the following configuration:
I have done no settings in Global.asax nor anything is web.config . I have seen many forum wherein Global.asax and web.config is configured.
I want to know what do i need to do in my project in order to be very efficient to work. I am facing problem with session timeout. I have set it to 20 mins on my server but sometimes suddenly i get logged out.
Please help me to understand using session for authentication.
First of all you have to edit web.config and set session timeout attribute.
<configuration>
<system.web>
<sessionState timeout="200"></sessionState>
</system.web>
</configuration>
Another issue is the use of IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["login"] != null && Session["db"] != null)
{
String DB = "";
String AccountID = "";
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
else
{
Response.Redirect("log.aspx");
}
}

Preserving CheckBox's Value in Dynamic GridView TemplateField

I am trying to create a GridView which will contain a list of users and permission levels that they have access to. Each row will have the following fields: User_ID, Username, Permission1, Permission2, ..., PermissionN, where the values of permissions field are "0" if the user does not have that permission and "1" if they do (note that columns returned by the DAL are not named Permission1, but rather are the actual name of the permission). I would like to represent the data by using CheckBoxes, to allow an admin to quickly grant or revoke permissions to a large number of users at once.
Since I will not know the number of permissions before-hand, I dynamically create TemplateFields and CheckBoxes, and this works fine; the GridView shows the current permission levels of all the users. I run into a problem when I try to update permissions based on the user checking and unchecking boxes.
Once the user is done changing permissions, I have an "Update" button, which of course causes a postback. Since the postback occurs before the OnClick event, by the time I reach OnClick all of the CheckBoxes have been reset to their initial values. Is there a way I can somehow grab the value of the CheckBoxes' Checked property before the postback occurs? Is there another (better) way of doing this? Thanks.
ASPX:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataKeyNames="ID">
</asp:GridView>
<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GET_USERS"
TypeName="oDAL">
</asp:ObjectDataSource>
<asp:Button ID="btnUpdate" runat="server" Text="Update Permissions" OnClick="btnUpdate_OnClick"/>
Code Behind:
private static string[] excludeCols = { "ID", "Username" };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Removing the IsPostBack check refreshes the GridView when the Update button is clicked
bindGridViewWithHiddenID(gvUsers, ((DataView)odsUsers.Select()).Table, excludeCols);
}
public static bool bindGridViewWithHiddenID(GridView gv, DataTable dt, string[] excludeCols)
{
gv.Columns.Clear();
gv.DataBind();
if (gv != null && dt != null && dt.Rows.Count > 0)
{
DataControlField newField;
foreach (DataColumn column in dt.Columns)
{
if (excludeCols.Contains(column.ColumnName))
{
newField = new BoundField();
((BoundField)newField).DataField = column.ColumnName;
}
else
{
newField = new TemplateField();
((TemplateField)newField).ItemTemplate = new CustomTemplate(column.ColumnName);
}
newField.HeaderText = column.ColumnName;
if (column.ColumnName == "ID" || column.ColumnName.EndsWith("_ID"))
newField.Visible = false;
gv.Columns.Add(newField);
}
gv.DataSource = dt;
gv.DataBind();
return true;
}
return false;
}
// By this time execution reaches here the CheckBoxes have already been reset
protected void btnUpdate_Click(object sender, EventArgs e)
{
...
}
CustomTemplate class:
public class CustomTemplate : ITemplate
{
private string binding;
private static int count = 0;
public CustomTemplate(string colNameBinding)
{
binding = colNameBinding;
}
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + count++;
chk.DataBinding += new EventHandler(this.chk_OnDataBinding);
container.Controls.Add(chk);
}
public void chk_OnDataBinding(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow namingContainer = (GridViewRow)chk.NamingContainer;
DataRowView dataRow = (DataRowView)namingContainer.DataItem;
if (dataRow[binding].ToString() == "1")
chk.Checked = true;
else
chk.Checked = false;
}
This behavior is expected and is normal. It has to do with the Page Life cycle and tracking of ViewState on dynamically added controls. I recommend you read this article from Scott Mitchell, specially the section titled: View State and Dynamically Added Controls.
I tried adding the GridView binding to OnInit() but since the CheckBoxes aren't actually instantiated until the GridView is DataBound, and since DataBinding will revert the GridView back to its original state, I seem to be stuck again.

The ControlToValidate property of 'NameValid' cannot be blank

i m writing a web application and i have a problem in one on my pages!
i design a admin page and i want to log in before user enter in this page!
there are three RequiredFieldValidator and a button(AddButton) in my page and i want to check the fields when user click the button but when the page is loaded the validation is checked and visual studio throw a exception:
"The ControlToValidate property of 'NameValid' cannot be blank" NameValid is one of my Validation controls in page!
and another question: what is the advantage of (using) block when you work with databases and files?
my class is here:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//a page for log in
Response.Redirect("~/LogIn.aspx");
}
}
protected void Page_Error(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<h2>Exception</h2><br />");
Response.Write(Server.GetLastError().Message);
Server.ClearError();
}
protected void AddButton_Click(object sender, EventArgs e)
{
const string ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\rasoul\sourcecode\ASP-PROJECTS\UniversityDataBase\DataBase\PersonDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection con=new SqlConnection(ConnectionString))
{
string ID = IDField.Text.Trim();
string Name = NameField.Text.Trim();
string LastName = LastNameField.Text.Trim();
DataSet data = new DataSet();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("insert into StudentTable values('{0}','{1}','{2}')", ID, Name, LastName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
what should i do?
In required field validators you MUST specify the ControlToValidate - the control you which to validate that it is required.
MSDN Description - Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. (Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx)
The advantage of the using block is it ensures the correct use of IDisposable objects.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
is equivalent to
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Source: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
you have to check controltovalidate. you have to assign controller.

LINQ: custom column names

UPDATE
I'm basically binding the query to a WinForms DataGridView. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.
How do you create your own custom column names in LINQ?
For example:
Dim query = From u In db.Users _
Select u.FirstName AS 'First Name'
As CQ states, you can't have a space for the field name, you can return new columns however.
var query = from u in db.Users
select new
{
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FirstName + " " + u.LastName
};
Then you can bind to the variable query from above or loop through it whatever....
foreach (var u in query)
{
// Full name will be available now
Debug.Print(u.FullName);
}
If you wanted to rename the columns, you could, but spaces wouldn't be allowed.
var query = from u in db.Users
select new
{
First = u.FirstName,
Last = u.LastName
};
Would rename the FirstName to First and LastName to Last.
I solved my own problem but all of your answers were very helpful and pointed me in the right direction.
In my LINQ query, if a column name had more than one word I would separate the words with an underscore:
Dim query = From u In Users _
Select First_Name = u.FirstName
Then, within the Paint method of the DataGridView, I replaced all underscores within the header with a space:
Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
For Each c As DataGridViewColumn In DataGridView1.Columns
c.HeaderText = c.HeaderText.Replace("_", " ")
Next
End Sub
If you want to change the header text, you can set that in the GridView definition...
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
</Columns>
</asp:GridView>
In the code behind you can bind to the users and it will set the header to First Name.
protected void Page_Load(object sender, EventArgs e)
{
// initialize db datacontext
var query = from u in db.Users
select u;
GridView1.DataSource = query;
GridView1.DataBind();
}
You can also add an event handler to replace those underscores for you!
For those of you who love C#:
datagrid1.ItemDataBound +=
new DataGridItemEventHandler(datagrid1_HeaderItemDataBound);
And your handler should look like this:
private void datagrid1_HeaderItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach(TableCell cell in e.Item.Cells)
cell.Text = cell.Text.Replace('_', ' ');
}
}
I would use:
var query = from u in db.Users
select new
{
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FirstName + " " + u.LastName
};
(from Scott Nichols)
along with a function that reads a Camel Case string and inserts spaces before each new capital (you could add rules for ID etc.). I don't have the code for that function with me for now, but its fairly simple to write.
You can make your results have underscores in the column name and use a HeaderTemplate in a TemplateField to replace underscores with spaces. Or subclass the DataControlField for the GridView and override the HeaderText property:
namespace MyControls
{
public SpacedHeaderTextField : System.Web.UI.WebControls.BoundField
{ public override string HeaderText
{ get
{ string value = base.HeaderText;
return (value.Length > 0) ? value : DataField.Replace(" ","");
}
set
{ base.HeaderText = value;
}
}
}
}
ASPX:
<%#Register TagPrefix="my" Namespace="MyControls" %>
<asp:GridView DataSourceID="LinqDataSource1" runat='server'>
<Columns>
<my:SpacedHeaderTextField DataField="First_Name" />
</Columns>
</asp:GridView>
I dont see why you would have to do that, if you are trying to do that for a grid or something, why not just name the header in the HTML?
What you would actually be doing is setting a variable reference to the return, there is not a way to name a variable with a space. Is there an end result reason you are doing this, perhaps if we knew the ultimate goal we could help you come up with a solution that fits.
Using Linq Extension Method:
SomeDataSource.Select(i => new { NewColumnName = i.OldColumnName, NewColumnTwoName = i.OldColumnTwoName});
As others have already pointed out, if the header title etc is known at design time, turn off AutoGeneratedColumns and just set the title etc in the field definition instead of using auto generated columns. From your example it appears that the query is static and that the titles are known at design time so that is probably your best choice.
However [, although your question does not specify this requirement] - if the header text (and formatting etc) is not known at design time but will be determined at runtime and if you need to auto generate columns (using AutoGenerateColumns=
true") there are workarounds for that.
One way to do that is to create a new control class that inherits the gridview. You can then set header, formatting etc for the auto generated fields by overriding the gridview's "CreateAutoGeneratedColumn". Example:
//gridview with more formatting options
namespace GridViewCF
{
[ToolboxData("<{0}:GridViewCF runat=server></{0}:GridViewCF>")]
public class GridViewCF : GridView
{
//public Dictionary<string, UserReportField> _fieldProperties = null;
public GridViewCF()
{
}
public List<FieldProperties> FieldProperties
{
get
{
return (List<FieldProperties>)ViewState["FieldProperties"];
}
set
{
ViewState["FieldProperties"] = value;
}
}
protected override AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
{
AutoGeneratedField field = base.CreateAutoGeneratedColumn(fieldProperties);
StateBag sb = (StateBag)field.GetType()
.InvokeMember("ViewState",
BindingFlags.GetProperty |
BindingFlags.NonPublic |
BindingFlags.Instance,
null, field, new object[] {});
if (FieldProperties != null)
{
FieldProperties fps = FieldProperties.Where(fp => fp.Name == fieldProperties.Name).Single();
if (fps.FormatString != null && fps.FormatString != "")
{
//formatting
sb["DataFormatString"] = "{0:" + fps.FormatString + "}";
field.HtmlEncode = false;
}
//header caption
field.HeaderText = fps.HeaderText;
//alignment
field.ItemStyle.HorizontalAlign = fps.HorizontalAlign;
}
return field;
}
}
[Serializable()]
public class FieldProperties
{
public FieldProperties()
{ }
public FieldProperties(string name, string formatString, string headerText, HorizontalAlign horizontalAlign)
{
Name = name;
FormatString = formatString;
HeaderText = headerText;
HorizontalAlign = horizontalAlign;
}
public string Name { get; set; }
public string FormatString { get; set; }
public string HeaderText { get; set; }
public HorizontalAlign HorizontalAlign { get; set; }
}
}
I believe this can be achieved using explicit name type
system.Name,
sysentity.Name
//change this to
entity = sysentity.Name
My VS2008 is busted right now, so I can't check. In C#, you would use "=" - How about
Dim query = From u In db.Users _
Select 'First Name' = u.FirstName

Resources