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>
Related
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.
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.
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";
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)?
I have a website in which I am migrating membership from ASP.NET services to a custom provider. I would like to migrate existing users without them needing to change their passwords.
The users' passwords are currently stored using a one-way encryption. The only option for me is to use the same salt and passwords as the ASP services and validate against them with my custom provider.
Here is the configuration used to currently hash the passwords with ASP.NET services.
<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="15" hashAlgorithmType="">
<providers>
<clear/>
<add connectionStringName="dashCommerce" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="dashCommerce" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" passwordStrengthRegularExpression="" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</membership>
I have been pulling my hair out trying to write the code needed to validate passwords against hashes generated by this config.
This is what I have so far. Any help would be greatly appreciated.
private static string CreatePasswordHash(string Password, string Salt)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(Password + Salt, "SHA1");
}
//string hashOldPassword = utl.generateHash(txtpassword.Text);
string hashOldPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtpassword.Text,"SHA1");
//string hashOldPassword = Membership.Provider.GetPassword(Page.User.Identity.Name.ToString(), string.Empty);
MembershipUser user = Membership.GetUser();
//string hashOldPassword = user.GetHashCode(
if (txtnewpassword.Text.Length < 7)
{
}
var userId = user.ProviderUserKey;
var user1 = Membership.GetUser();
MembershipPasswordFormat passwordFormat;
string passwordSalt;
string password;
SqlConnection sqlconn = new SqlConnection(Connect.Connection());
//var cstring = ConnectionStrings[Connect.Connection()];
using (var conn = new SqlConnection(sqlconn.ConnectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select PasswordFormat,PasswordSalt,Password from aspnet_Membership where UserId=#UserId";
cmd.Parameters.AddWithValue("#UserId", userId);
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr != null && rdr.Read())
{
passwordFormat = (MembershipPasswordFormat)rdr.GetInt32(0);
// passwordFormat = rdr.GetString(0);
passwordSalt = rdr.GetString(1);
password = rdr.GetString(2);
if (hashOldPassword == password)
{
user.ChangePassword(txtpassword.Text, txtnewpassword.Text);
}
else
{
}
//if(password.ToString()!=txtpassword)
}
else
{
throw new Exception("An unhandled exception of type 'DoesntWorkException' has occured");
}
}
I dug through reflector and found the code used to compute hashes.
private static string CreatePasswordHash(string Password, string Salt)
{
string passwordFormat = SettingManager.GetSettingValue("Security.PasswordFormat");
if (String.IsNullOrEmpty(passwordFormat))
passwordFormat = "SHA1";
byte[] bytes = Encoding.Unicode.GetBytes(Password);
byte[] src = Convert.FromBase64String(Salt);
byte[] dst = new byte[src.Length + bytes.Length];
byte[] inArray = null;
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create(passwordFormat);
inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
This worked.