It is possible to use app keys for all the connection string inputs and read those on connection string like bellow
<add name="DefaultConnection" connectionString="Data Source=$(Server);Initial Catalog=$(Catalog);User ID=$(User);Password=$(Password)" providerName="System.Data.SqlClient" />
<add key="$(Server)" value="xxxx" />
<add key="$(Catalog)" value="xxxx" />
<add key="$(User)" value="xxxx" />
<add key="$(Password)" value="xxxx" />
As #Ertürk Öztürk already say - it's not possible.
If you searching for more or less clean way to do it i suggest you to use SqlConnectionStringBuilder or DbConnectionStringBuilder if you using not MSSQL data base.
In your code it will be like this with SqlConnectionStringBuilder:
//create connection string builder
System.Data.SqlClient.SqlConnectionStringBuilder connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
//set all properties from your WebConfig
connectionStringBuilder.DataSource = ConfigurationManager.AppSettings["Server"];
connectionStringBuilder.InitialCatalog = ConfigurationManager.AppSettings["Catalog"];
connectionStringBuilder.UserID = ConfigurationManager.AppSettings["User"];
connectionStringBuilder.Password = ConfigurationManager.AppSettings["Password"];
//not you can get rigth formatted connection string
var connectionString = connectionStringBuilder.ConnectionString;
It's not possible. Actually you don't need to do this, that's why it's not possible. Because you can change the other parts of web.config same like AppSettings.
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString =
String.Format("Data Source={0};Initial Catalog={1};UserID={2};Password={3}",
"server", "db", "ID", "Pass");
Related
I am using Membership in .net web application.
I have the following web.config configuration...
<profile ...>
.....
<properties>
<add name="FirstName"/>
<add name="LastName"/>
<add name="DateOfBirth" type="DateTime"/>
.....
</properties>
</profile>
I inserted data using the following code segment, which affected the aspnet_profile database table.
dynamic profile = ProfileBase.Create("Username");
profile.Initialize("Username", true);
profile.FirstName = "someFirstName";
profile.LastName = "someLastName";
profile.Save();
Now please anyone suggest me how to retrieve this data.
Now please anyone suggest me how to retrieve this data.
You can use System.Web.Profile.ProfileManager and then its API like FindProfilesByUserName(), GetAllProfiles() etc.
Here is already a solved thread.
This is what i did to retrieve profile property value...
string Firstname = ProfileBase.Create("UserName").GetPropertyValue("FirstName").toString();
In my "web store" mvc app I want to add items to database. Items table has CreatedBy field and it is a foreign key from User table UserId field. Everything was working before I put the database into the App_Data folder. Now I get the SqlException when trying to create a new Item:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Item_contains_User". The conflict occurred in database "C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF", table "dbo.Users", column 'UserId'.
Here is the Create method of ItemRepository class:
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
Here is the controller method Create:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
Besides, I use Linq to Sql model drag an' drop approach.
Here is the changed web.config connection string part:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
As I said everything was working before I moved the database to App_Data file. I also tried to remove the dependency between Items and Users tables - the exact same exception.
Any help would be appropriate. Thanks in advance!
Edits:
Ok, now I really broke the dependency between Items and Users tables and no exception occures. But! I have to somehow know who has created each product, so breaking the dependency is not an option. I also tried to remove all code that initializes the CreatedBy field.
Any ideas??
Edits (part 2):
The second comment below gives a great advise! I found that all users that are created are stored now in the aspnet.sdf database!!!
But if I remove the connection string "DeafaultConnection":
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I will get ConfigurationErrorsException:
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
in the folowing line:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
Ok, as I guessed the issue was in the configuration. Each provider (for some reason) in the connection string had "DefaultConnection". I changed it to "WebStoreConnectionString". And now everything works!
p.s. thanks #w0lf, he pushed the thoughts in the right direction)
How do I retrieve both the Server Name and Database Name from a web.config connection string programatically through the .net api? Preferably without using an html or xml parser I create. Looking for the simplest way to retrieve this type of information.
Example web.config snippet:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Provider=SQLOLEDB;Data Source=MyServer;User ID=admind;password=ju7mpst#rterz_Fak3;Initial Catalog=dbDatabase" providerName="System.Data.OLEPlethora"/>
</connectionStrings>
<system.web>
result:
server=MyServer
database=dbDatabase
Found this link regarding retreiving connection string settings. This appears to be much simplier, however, I'm not sure if I can iterate over many connection string.
Get the connectionstring from config as such:
var myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
You can then use the oledb connectionstring builder to parse any connectionstring and extract the relevant parts.
var builder = new System.Data.OleDb.OleDbConnectionStringBuilder(myConnectionString);
var servername = builder["Data Source"];
var database = builder["Initial Catalog"];
Console.WriteLine("server={0}, database={1}", servername, database);
I have a basic 1 table grid. I have a field called Branch type. The branch type can only be Corporate or Franchise. When i click on the edit button on the ASPxgridview row , i would like to display and hide fields on the edit form, depending on what Branch Type it is. So if it is Corporate i would like to Display the Manager field and Hide the Owner field. When the branch type is Franchise then I would like the Owner field to be displayed and the Manager field to be hidden on the edit form. all details can show on the grid view but on the edit form i would like to force the user to only fill in applicable fields.
If you look below:
this is basically what i want to achieve on loading the edit form :
protected void ASPxGridViewStores_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (!ASPxGridViewStores.IsEditing || e.Column.FieldName != "StoreOwnershipID") return;
if(e.KeyValue == DBNull.Value || e.KeyValue == null) return;
object val = ASPxGridViewStores.GetRowValuesByKeyValue(e.KeyValue, "S_ID");
if(val == DBNull.Value) return;
int StoreOwnershipID = (Int32)val;
if (StoreOwnershipID == 4)
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = true;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = true;
}
else
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = false;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = false;
}
}
and then depending on selecting Corporate or Franchise in the "StoreOwnershipID" field i will use the client side script to enable or disable the additional fields.
I have done some research as well, and i came up with the following code:
SelectedIndexChanged="function(s, e) {
var value = s.GetValue();
if(value == 4)
GridViewStores.GetEditor("OwnerName").SetVisible(true);
else
GridViewStores.GetEditor("OwnerName").SetVisible(false);
}"
but when this is called i get the following error:
Microsoft JScript runtime error: 'GridViewStores' is undefined
I have added the HTTPhandler in the web.config:
<httpModules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</httpModules>
and
<system.webServer>
<modules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</modules>
as you can see below i have inserted the ClientInstanceName,
i have changed the ClientIDMode from AutoID to Inherit to Static to Predictable and each scenario does not work and still renderes : Microsoft JScript runtime error: 'ASPxGridview' is undefined.
below my gridview tag
<dx:ASPxGridView ID="ASPxGridView" runat="server" AutoGenerateColumns="False"
ClientIDMode="Predictable" DataSourceID="SqlDataSource1" KeyFieldName="S_ID"
ClientInstanceName="ASPxGridView">
i have now even tried creating a new page with just a sqldatasource and gridview with the storetype field as acombobox and including the javascript as mentioned in my previous posts.. and no luck at all. i have given you my web.config settings where i declared the httphandler, so what else do you suggest i do to get this working?
here is my webconfig:
section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<httpModules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</httpModules>
<httpHandlers>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" validate="false" />
</httpHandlers>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
sorry for the looong question. by the way this is using DevExpress Gridview. The guys from devexpress cant help me and tak 1 day to answer a question, so its been going on for almost a week now...
Thank you
Werner
The Java Script is a case sensitive language. So, if the ClientInstanceName is set to ASPxGridView, your code should be:
ASPxGridView.GetEditor("OwnerName").SetVisible(true);
I see that the error message contains the 'ASPxGridview;' identifier. It means that your code contains the ASPxGridview identifier but you should use the ASPxGridView (based on your mark up). Also, I believe that this code is wrong:
if (StoreOwnershipID == 4)
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = true;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = true;
}
else
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = false;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = false;
}
You set the Enabled property of the ManagerID object twice to the same value. Please check it. I have nothing to add. if this does not help, please let me know the support center ticket ID and if possible attach the source code of the page (cs and aspx) and web.config there. We will try to help you.
Update: I have found your question in the support center and answered it. Hope, this helps.
Is there an utility or code sample that can decrypt with the old key, and then encrypt passwords with a new key for ASP.Net membership users?
None of the workarounds mentioned worked for me.
My solution is below. It involves first storing passwords in clear text and then reencrypting them again with new MachineKey.
Machine Key Change
This is my best guess at a solution, but I haven't had a chance to test it. It relies on the following settings for your current provider:
enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" passwordFormat="Encrypted"
It also assumes that the new machinekey is already in the config file.
Create the following class (thanks to mootinator for the jumpstart on this)
using System.Reflection;
using System.Web.Configuration;
using System.Web.Security;
namespace MyNamespace
{
public class MySqlMembershipProvider : SqlMembershipProvider
{
protected override byte[] DecryptPassword(byte[] encodedPassword)
{
MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
section.DecryptionKey = "oldkey"; // TODO: Set your old key here
MethodInfo method = typeof(MachineKeySection).GetMethod("EncryptOrDecryptData", BindingFlags.Instance | BindingFlags.NonPublic);
return (byte[])method.Invoke(section, new object[] { encodedPassword, null, 0, encodedPassword.Length, 0, false, false });
}
}
}
In your web.config:
<membership defaultProvider="DefaultSqlMembershipProvider">
<providers>
<clear/>
<add name="DefaultSqlMembershipProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" applicationName="TODO" passwordFormat="Encrypted" type="System.Web.Security.SqlMembershipProvider"/>
<add name="MySqlMembershipProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" applicationName="TODO" passwordFormat="Encrypted" type="MyNamespace.MySqlMembershipProvider"/>
</providers>
</membership>
Change the passwords with the following code:
MembershipProvider retrievePasswordProvider = Membership.Providers["MySqlMembershipProvider"];
foreach (MembershipUser user in Membership.GetAllUsers())
{
MembershipUser retrievePassworedUser = retrievePasswordProvider.GetUser(user.UserName, false);
string password = retrievePassworedUser.GetPassword(); // get password using old key
user.ChangePassword(password, password); // change password to same password using new key
}
Let me know if that works for you.
I think you could do this by setting the key on the fly:
You might have to extend the SqlMembershipProvider (or whatever you use) to get access to the protected DecryptPassword method.
MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
section.DecryptionKey = "old";
// Read old password
section.DecryptionKey = "new";
// Store new password