how to access connection string Class.cs file? - asp.net

I am totally new to Windows programming so i don't know how to access connection string in Class.cs file as we can in web application as follow:
public DataTable Client_Login_Check(string Email, string Password)
{
DataTable dt = new DataTable();
try
{
object[] objParam = new object[2];
objParam[0] = Email;
objParam[1] = Password;
return dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["GL"], "GreenLight_Users_LoginCheck", objParam).Tables[0];
}
catch (Exception ex)
{
OutputMessage = ex.Message;
}
return dt;
}
I have added "System.Configuration" namespace...But still i am not getting ConfigurationManager in help. Please help me..

Apart from adding a reference to System.Configuration.dll in the project, you will also need to add a using declaration for the namespace in the file:
using System.Configuration;
Note:
You should be using ConfigurationManager.ConnectionStrings["GL"].ConnectionString and have the connection string in the connectionStrings configuration section, not in the appSettings section.

Add a reference to System.Configuration.dll, and you should be able to use the System.Configuration.ConfigurationManager

if you want to use App.config
add these lines in tag
<configuration>
<connectionStrings>
<add name="mystring" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=dbName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="Server" value=".\SQLEXPRESS"/>
<add key="Database" value="dbAIAS"/>
<add key="ClientSettingsProvider.ServiceUri" value=""/>
</appSettings>
<configuration>
in Name.cs file you can access by
string strconn = #"Data Source= " + ConfigurationSettings.AppSettings["Server"].ToString() + "; Initial Catalog= " + ConfigurationSettings.AppSettings["Database"].ToString() + ";Integrated Security=True";

Related

angularjs - webservice returns an html page instead of data

I'm using $http.get to connect to an asmx webservice passing 2 parameters: username and password. However it returns the html page of the web service instead of data.
am I missing something?
here's my code for controller.js:
$scope.enterlogin = function(usern,pass)
{
loginService.getUser(usern,pass).then(function(response){
console.log('response is = ' + response.data);
};
}
Here's my code for services.js:
.factory('loginService', ['$http', function($http){
var base_url = "http://<ipaddress of webservie>/UserService3/WebService1.asmx?op=getUserbyUsername";
return {
getUser: function(usern,pass){
console.log('code side usern is = ' + usern + "" + pass);
return $http.get(base_url, { params: { passw: pass, uname: usern}
});
}
}
}])
I also added these to the webservice's web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpHandlers>
<add verb="GET,HEAD,POST,OPTIONS" path="*.asmx" type="System.Web.UI.PageHandlerFactory" />
</httpHandlers>
And this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
and this is the webmethod in the webservice:
[WebMethod]
public string getUserbyUsername(string uname, string passw)
{
string cs = "Data Source =.; Initial Catalog = UsersDB; Integrated Security = True";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetUserByUsername", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter(#"Username", uname);
SqlParameter parameter2 = new SqlParameter(#"Password", passw);
cmd.Parameters.Add(parameter);
cmd.Parameters.Add(parameter2);
User user = new User();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// user.Username = reader["Username"].ToString();
// user.Password = reader["Password"].ToString();
user.IsExisting = reader["IsExisting"].ToString();
user.UserID = reader["UserID"].ToString();
}
con.Close();
return new JavaScriptSerializer().Serialize(user);
}
}
You might need to change System.Web.UI.PageHandlerFactory (which is typically used for aspx endpoints) to System.Web.Services.Protocols.WebServiceHandlerFactory (which is more typically used for asmx endpoints).
EDIT: try changing the return to void and then doing this:
Context.Response.Write(new JavaScriptSerializer().Serialize(user));
See if that works.

'Unicode' is an invalid connection string attribute Asp.net

My code have error ---- 'Unicode' is an invalid connection string attribute
Web Config :
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=XE;Persist Security Info=True;User ID=****;Password=****;Unicode=True"
providerName="System.Data.OracleClient" /> </connectionStrings>
Asp.net:
public DataTable Bankomat(DataTable dt)
{
using (con = new OracleConnection())
{
using (cmd = new OracleCommand())
{
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString();
cmd.Connection = con;
cmd.CommandText = "select * from bankomat";
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
}
return dt;
}
In the connection string
connectionString="Data Source=XE;Persist Security Info=True;User ID=****;Password=****;Unicode=True"
the Unicode=True is belong to System.Data.OracleClient and not to Oracle.DataAccess.Client
So just remove it.

How to get the session details from sql server database

I have one Solution which has different projects like ASP.Net
and ASP.Net MVC in this solution. When the user logs in to the
application, the same credentials I need to pass to the other project
in same solution. It should not ask credentials again, because he has
already logged in. For that I have stored the session details in the sql
server database using the SqlServer mode. But the problem is I am unable
to get the session which is stored in the database.
Any help on this will be appreciated. Thanks in advance.
This is what i have tried to fetch data from ASPState database
public ActionResult Home()
{
ViewBag.Result =Session["username"].ToString();
SqlCommand cmd = new SqlCommand("select SessionId from
ASPStateTempSessions", con);
byte[] bytdata = new byte[50];
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
var list = new List<LoginUser>();
if(dr.HasRows)
{
while(dr.Read())
{
//obj=dr["SessionId"];
string obj = dr["SessionId"].ToString();
bytdata = System.Text.Encoding.UTF8.GetBytes(obj);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytdata);
BinaryFormatter bin = new BinaryFormatter();
//bin.Serialize(ms, bytdata);
//list = (List<LoginUser>)bin.Deserialize(ms);
string session = Convert.ToString(bin.Deserialize(ms));
}
}
ViewBag.Data = list;
return View();
}
This is what i have configured ion Web.config
<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="SessionSqlCon" cookieless="false" timeout="10" />
</providers>
</sessionState>

Uploaded website does not sent emails

I have uploaded my website to a known hosting server and i have a contact form, the weird thing is that when i run the website from visual studio (asp.net language) is sending the emails fine on my inbox.From the time that i uploaded it on the hosting server it gives the error: failure sending the email.I am using smtp.gmail.com, port:587,username and pass and ssl enabled.
protected void sendClientMail(string emailto)
{
try
{
var mail = new MailMessage
{
BodyEncoding = Encoding.UTF8,
From = new MailAddress(ConfigurationManager.AppSettings["MAILFROM"])
};
mail.To.Add(emailto);
mail.Bcc.Add(ConfigurationManager.AppSettings["MAILBCC"]); //sends to my email also
mail.Subject=ConfigurationManager.AppSettings["CLIENT-MAILSUBJECT"];
mail.IsBodyHtml = true;
#region //Load Email Control and get HTML string
string mailBody = "";
{
PrintPlaceHolder.Visible = true;
var sb = new StringBuilder();
var writer = new HtmlTextWriter(new StringWriter(sb));
var emailctl = LoadControl("~/Controls/ClientEmail.ascx") as ClientEmail;
if (emailctl != null)
{
emailctl.Name = txtName.Text;
emailctl.IntroName = txtName.Text + " " + txtSurname.Text;
emailctl.Surname = txtSurname.Text;
emailctl.Mobile = txtMobile.Text;
emailctl.Phone = txtPhone.Text;
emailctl.City = txtCity.Text;
emailctl.Street = txtStreet.Text;
emailctl.Message = txtmessage.Text;
emailctl.Email = txtEmail.Text;
emailctl.Country = ddlCountry.SelectedValue;
PrintPlaceHolder.Controls.Add(emailctl);
emailctl.RenderControl(writer);
}
mailBody = sb.ToString();
if (emailctl != null)
{
emailctl.Dispose();
}
writer.Dispose();
sb.Clear();
PrintPlaceHolder.Visible = false;
}
#endregion
mail.Body = mailBody;
//mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential (ConfigurationManager.AppSettings["MAILFROM"], ConfigurationManager.AppSettings["PASS"]);
client.Host = ConfigurationManager.AppSettings["SMTPSERVER"];
client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPORT"]);
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl= false;
//client.UseDefaultCredentials = true;
client.Send(mail);
clearFields();
Response.Write("<script>alert('"+ConfigurationManager.AppSettings["MAILSUCCESS"]+"');</script>");
}
catch (Exception e)
{
Response.Write("<script>alert('"+ ConfigurationManager.AppSettings["MAILFAIL"] +" Error: "+e+"')</script>");
}
}//end method
Web.config file code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="CLIENT-MAILSUBJECT" value="Mario Website - Confirmation Email"/>
<add key="MY-MAILSUBJECT" value="Mario Website - Email Sent"/>
<add key="MAILFROM" value="mariotec#mario26tech.com"/>
<add key="MAILBCC" value="nikolaou_marios#hotmail.com"/>
<add key="SMTPSERVER" value="sns41.win.hostgator.com"/>
<add key="SMTPPORT" value="26"/>
<add key="PASS" value="pass"/>
<add key="MAILSUCCESS" value="Email was sent successfully, thank you for your interest!!!"/>
<add key="MAILFAIL" value="There was an error while sending the email."/>
</appSettings>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear/>
<add value="Index.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
I have contacted the hosting provider without any help.
Thanks in advance.

ConnectionStringSettings NullReference Error

I have the following settings in my web.config, as a child of the configuration element:
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
In the code behind where I wish to retrieve the connection string, I placed:
using System.Configuration
...
var connStringObject = ConfigurationManager.ConnectionStrings["GingerlimeDB"];
string connectionString = connStringObject.ConnectionString;
Console.WriteLine(connectionString);
I don't get to the console output, instead it shows:
Object reference not set to an instance of an object.
How do I get the Connection String out of the web config?
Assuming your web.config file looks like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You should be able to access the connection string exactly like you showed in your code. I use something nearly identical:
using System.Configuration;
....
internal bool OpenDatabaseConnection()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
dbConnection = new SqlCeConnection(connectionString);
dbConnection.Open();
return true;
}
catch (SqlCeException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (InvalidOperationException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ArgumentException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ConfigurationErrorsException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
return false;
}
Which line is actually causing the NullReference exception? (object not set to an instance of an object)?

Resources