asp.net mvc 3 web.config connection string encryption - asp.net-mvc-3

I have to deploy an asp.net mvc 3 website and its web.config contains database credentials.
After searching for a while, I found that one could place the connection string in a .cs file in App_Data folder, but if database password is changed, then the site needs to be recompiled.
Also I got to this link: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA , but the page says that the content is not retired.
Can someone please tell the updated practices to encrypt the connection string information in the web.config file.
Thanks.

Using an encrypt/ decrypt method on the particular web.config file
still seems to be the preferred practice
Classic implementation programmatically
I don't think the practices of encrypting web.config has updated with MVC, other than, obviously, you can't use an Event button to call the method as in the above example. You want to map the Encrypt/Decrypt methods to a controller action.
public ActionResult Encrypt()
{
ProtectSection("connectionStrings", "RSAProtectedConfigurationProvider");
return View();
}
private void ProtectSection(string sectionName,
string provider) {
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section =
config.GetSection(sectionName);
if (section != null &&
!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}}

To Encrypt Connection string in Web.Config files, We can follow these steps.
Open C:\Windows\System32\CMD.exe As Administrator
In CMD type CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319 In CMD type
aspnet_regiis.exe -pef connectionStrings “Path of the Folder
containing the Web.Config file”
Ex: aspnet_regiis.exe -pef “connectionStrings” “D://PROJECTS/SAMPLE_PROJECT”
Set to identity impersonate false for project web.config
<system.web>
<identity impersonate="true" />
</system.web>
For Decryption, you can use the below command.
Open C:\Windows\System32\CMD.exe As Administrator
In CMD type CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
In CMD type aspnet_regiis.exe -pdf “connectionStrings” “Path of the Folder containing the Web.Config file”
Ex: aspnet_regiis.exe -pdf “connectionStrings” “D://PROJECTS/SAMPLE_PROJECT”
Give thubms up to my article

Related

How to upload to SFTP user's Home directory using Spring Integration

I'm trying to upload a file via SFTP using Spring Integration (version 4.1.2).
Does anyone know how to configure the sftp:outbound-channel-adapter so that the file gets uploaded automatically to user's home directory without indicating the full directory path in the remote-directory's attribute (ex: remote-directory="/home/sftp_user")?
The solution is that the remote-directory must be set as an empty string.
Please note that the following won't work as it fails the XML model validation:
<sftp:outbound-channel-adapter
...
remote-directory=""
...
/>
I ended up reading the remote-directory from a configuration property which I set as an empty string.

SQLite with Entity Framework 6: relative path?

I'm trying to use SQLite with Entity Framework 6 in my WPF application. When I create Entity Data Model in the project, I connect to *.db file using absolute path, because relative path doesn't work for some reason. So my connection looks something like
<connectionStrings>
<add name="Model1ConnectionString" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SQLite.EF6;provider connection string='data source="C:\Users\gtmaster\Documents\Visual Studio 2017\Projects\SQLiteTest\SQLiteTest\test.db"'" providerName="System.Data.EntityClient" />
</connectionStrings>
If some other developer clones reporsitory with this connection he gets unable to open database file error, because absolute path to test.db in the project is obviously different on his machine.
How can I write relative path in app.config so entity models could work without changing it everytime?
using relative path for the DB file
the source of the db file is in App.config
<add name="ProjectDBEntities" connectionString="metadata=res://*/ProjectDBModel.csdl|res://*/ProjectDBModel.ssdl|res://*/ProjectDBModel.msl;provider=System.Data.SQLite.EF6;provider connection string='data source="c:\Users\Heckl\Documents\Dropbox\Else\visual studio\SqLiteTry\ProjectDB.db"'" providerName="System.Data.EntityClient"/>
the data source must be absoulte
you can use the |DataDirectory| substitution string in App.config
<add name="ProjectDBEntities" connectionString="metadata=res://*/ProjectDBModel.csdl|res://*/ProjectDBModel.ssdl|res://*/ProjectDBModel.msl;provider=System.Data.SQLite.EF6;provider connection string='data source="|DataDirectory|ProjectDB.db"'" providerName="System.Data.EntityClient"/>
the substitution string has to be set
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// ...
var db = new ProjectDBEntities()
problems:
exception at the first LINQ command
the change in App.config is not always detected by VS, you might have to rebuild solution manually
the code above set the location of the exe file in the solution\project\bin\debug folder
the db file is in the solution folder
check the value of db.Database.Connection.ConnectionString in a watch window during debug
you can copy the db file into the debug folder also
|DataDirectory| is good for production environment, but when you do update-database migrations apply to newly created database in EF packet directory, because EF cant get your project generated connection string and use self DataDirectory value.

Cannot find content file in bin folder

I have a IIS Express project running in debug mode in Visual Studio 2015.
The web application references a Class Library which has this line of code:
var certificate = new X509Certificate2(#"certkey.p12", "notasecret", X509KeyStorageFlags.Exportable);
The certkey.p12 file is in the same folder as the source code for the class library as is marked as "Build Action = Content" and "Copy if newer".
When I build, the file is copied to the web app's bin folder as expected. But when I call the method from the web app, it throws "file not found".
It works fine in Unit Testing where the file is copied to /bin/x64/Debug/
So where is IIS Express looking for the file? I suspect it is some sort of temp folder but why isn't VS copying the file there when I build/debug?
When running under IIS Express, it was looking for is "C:\Programs Files\IIS Express\certkey.p12".
I used a little peeking to find the folder that the file was actually copied to and came up with this:
string binPath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
Uri uri = new Uri(binPath);
string localPath = uri.LocalPath;
string dir = System.IO.Path.GetDirectoryName(localPath);
// now "dir" is the full local path of the bin folder
It is a little slow on first execute (~100ms) but faster on subsequent requests.
If there are any problems when I deploy this to production, I'll update.

Create a folder via IBM sbt and share it to specific user: what is the correct Userid format?

I'm trying to create a folder and share it to a specific user, using SBT in a standalone Java console application (JDK 7).
I started with FileServiceApp sample in sbt/samples, and modified it with the following code:
...
fsa = new FileServiceApp(url, user, password);
FileService fileService = fsa.getFileService();
File newFolder = fileService.createFolder(newFolderName, "description", shareWith);
shareWith is a String that must contain 3 comma separated values: id,(person/community/group),(reader/Contributor/owner) as described in:
http://infolib.lotus.com/resources/social_business_toolkit/javadoc/com/ibm/sbt/services/client/connections/files/FileService.html#createFolder%28java.lang.String,%20java.lang.String,%20java.lang.String%29
update: I just downloaded SBT 1.1.0 and createFolder no longer accepts the shareWith parameter.
But I keep getting a "Not found" error (if shareWith does not contains those 3 elements the error turns to "Bad request").
edited: Calling createFolder without the third parameter just works, but the folder is not shared of course.
I get the same behaviour if I try with the following (with sbt 1.1.0 too):
File newFolder = fileService.createFolder(newFolderName, "description");
Map<String, String> folderParameters = new HashMap<String, String>();
folderParameters.put("shareWith", userID);
folderParameters.put("sharePermission", "View");
fileService.updateFileMetadata(newFolder, folderParameters);
Userid should be correct at least for Smartcloud (the format is: 1f......-b...-4...-b...-f............2 for Greenhouse, 2......1 for Smartcloud). I verified it using ProfileService.getProfile(id), for Smartcloud.
Code has been executed over a greenhouse account, and a collabserv account, using BasicEndpoint in both cases (SmartCloudEndpoint for Smartcloud).
My questions are:
is "share folder" not available in SmartCloud / Greenhouse, and in that case, is it available for a standalone Connections instance?
am I missing anything? (I only put the jars in lib/ext)
Found that the correct format for FileService.createFolder third parameter was
GUID + ",user,reader"
and not GUID,person,reader. Where GUID is the user GUID as suggested by Paul (not tried with user email yet).

How to clone a WebSphere 8 profile

I would like to clone an existing profile, start the server and modify it via the Admin Console.
I already read the IBM documentation about
manageprofiles.bat
but the manageprofiles tool does not contain something like:
# would be nice if a clone action exists
manageprofiles.bat -clone -profileName base -targetProfileName base1
This is what I need and I don't see a way to achieve this.
The tool can create, delete, backup and restore a profile.
What I already tried
Copied the profile directory and renamed it
Edited the paths in the bin/setupCmdLine.bat
Added the profile to the AppServer/properties/profileRegistry.xml
Executed manageprofiles -validateAndUpdateRegistry
But the profile is still not recognized by WAS. I can verify this by executing
manageprofiles -listProfiles
How do you clone or copy profiles?
Is there a manual way?
If so, which files in the profile's dir must be edited?
Solved
Here are the manual steps that I did to clone an existent profile.
Make shure that the server is shutdown.
Copy the existent profile from Profiles/<oldProfile> to Profiles/<newProfile>
Update Path WAS_USER_SCRIPT in Profiles\<newProfile>\bin\setupCmdLine.bat
Update Path USER_INSTALL_ROOT in Profiles\<newProfile>\bin\setupCmdLine.bat
Update property user.root in Profiles\<newProfile>\properties\ssl.client.props
Replace all occurences of <oldProfile> with <newProfile> in Profiles\<newProfile>\firststeps\firststeps.bat
Edit AppServer\properties\profileRegistry.xml. Make a copy of the <oldProfile> and update the tag values with the <newProfile>. Should look something like this: <profile isAReservationTicket="false" isDefault="false" name="newProfile" path=".....\Profiles\newProfile" template=".......\AppServer\profileTemplates\default"/>
Copy AppServer\properties\fsdb\<oldProfile>.bat to AppServer\properties\fsdb\<newProfile>.bat. This step will make the profile available to "AppServer\bin\manageprofiles.bat -listProfiles"
Edit config/cells/<cell>/nodes/<node>/variables.xml. Update the USER_INSTALL_ROOT path.
Update the path of WAS_USER_SCRIPT in AppServer\properties\fsdb\<newProfile>.bat
This worked for me. Please comment or vote to let me know if it also worked for you.
Here is a build-in WebSphere solution. This works fine on WAS 8.5.5.3.
Run your application server in source profile
Run command line utility by running script <WAS_INSTAL_ROOT>/AppServer/profiles/<YOUR_SOURCE_PROFILE>/bin/wsadmin.sh or <WAS_INSTAL_ROOT>/AppServer/profiles/<YOUR_SOURCE_PROFILE>/bin/wsadmin.bat (on Windows machines)
Execute command in this utility:
$AdminTask exportWasprofile {-archive <PATH/TO/PROFILE/EXPORT/ARCHIVE>}
Create new target profile or use existing and run application server on it
Run command line utility for target profile by running script <WAS_INSTAL_ROOT>/AppServer/profiles/<YOUR_TARGET_PROFILE>/bin/wsadmin.sh or <WAS_INSTAL_ROOT>/AppServer/profiles/<YOUR_TARGET_PROFILE>/bin/wsadmin.bat (on Windows machines)
Execute command to import profile settings into target profile in this utility:
$AdminTask importWasprofile {-archive <PATH/TO/PROFILE/EXPORT/ARCHIVE> -deleteExistingServers}
Execute command to save new settings into target profile in this utility:
$AdminConfig save
I needed to do this today on WebSphere 8.5 Network Deployment, so I tracked it down and wrote a script. Here's how I do it.
Create a WebSphere profile using the GUI based Profile Management Tool.
Each one you create will write a log file to:
C:\Program Files (x86)\IBM\WebSphere\AppServer\logs\manageprofiles\XXXX_create.log
In the log, look for the -create switch. Clean up and copy that line into a script, modifying or parameterizing the fields as you wish:
SET PROFILENAME=Profile2
SET HOSTNAME=MyHostName
SET WAS_BIN=C:\Program Files (x86)\IBM\WebSphere\AppServer\bin
SET PROFILE_PATH=C:\Program Files (x86)\IBM\WebSphere\AppServer\profiles\%PROFILENAME%
SET WAS_TEMPLATE=C:\Program Files (x86)\IBM\WebSphere\AppServer\profileTemplates\default
SET WAS_CELL=%HOSTNAME%%PROFILENAME%Cell
SET WAS_PORTS_FILE=C:\Program Files (x86)\IBM\WebSphere\AppServer\logs\manageprofiles\was_default_portdef.props
SET A1=-create -serverName %PROFILENAME% -profileName %PROFILENAME% -cellName %WAS_CELL% -nodeName %PROFILENAME% -hostName %HOSTNAME%
SET A2=-profilePath "%PROFILE_PATH%" -templatePath "%WAS_TEMPLATE%"
SET A3=-applyPerfTuningSetting development -enableAdminSecurity false -winserviceCheck false -omitAction defaultAppDeployAndConfig
SET A4=-portsFile "%WAS_PORTS_FILE%"
SET A5=-signingCertDN "cn=10.0.2.15\\,ou=Root Certificate\\,ou=%WAS_CELL%\\,ou=%PROFILENAME%\\,o=IBM\\,c=US" -personalCertDN "cn=10.0.2.15\\,ou=%WAS_CELL%\\,ou=%PROFILENAME%\\,o=IBM\\,c=US"
SET A6=-personalCertValidityPeriod 10 -signingCertValidityPeriod 15
SET WAS_ARGS=%A1% %A2% %A3% %A4% %A5% %A6%
call "%WAS_BIN%\manageprofiles.bat" %WAS_ARGS%
You will need to look for the "C:\Program Files (x86)\IBM\WebSphere\AppServer\logs\manageprofiles*_portdef.props" files and copy one of them for your use as I did.
The output of my script was thus a cloned/tweaked version of a profile I had created before.
I then ran it at the commandline:
"C:\Program Files (x86)\IBM\WebSphere\AppServer\bin\manageprofiles.bat" -create -serverName Unica9103 -profileName Unica9103 -cellName UnicaVMUnica9103Cell -nodeName Unica9103 -hostName UnicaVM -profilePat
h "C:\Program Files (x86)\IBM\WebSphere\AppServer\profiles\Unica9103" -templatePath "C:\Program Files (x86)\IBM\WebSphere\AppServer\profileTemplates\default" -a
pplyPerfTuningSetting development -enableAdminSecurity false -winserviceCheck false -omitAction defaultAppDeployAndConfig -portsFile "C:\Program Files (x86)\IB
M\WebSphere\AppServer\logs\manageprofiles\was_default_portdef.props" -signingCertDN "cn=10.0.2.15\\,ou=Root Certificate\\,ou=UnicaVMUnica9103Cell\\,ou=Unica9103
\\,o=IBM\\,c=US" -personalCertDN "cn=10.0.2.15\\,ou=UnicaVMUnica9103Cell\\,ou=Unica9103\\,o=IBM\\,c=US" -personalCertValidityPeriod 10 -signingCertValidityPeri
od 15
Notice that the commas need to be escaped with double backslashes or you get cryptic errors.
You will get something like the following on success:
INSTCONFSUCCESS: Success: Profile Unica9103 now exists. Please consult C:\Program Files (x86)\IBM\WebSphere\AppServer\profiles\Unica9103\logs\AboutThisProfile.txt for more information about this profile.
I have not tested the method but wsadmin has the following command:
createAppServerTemplate
This script creates a new application server template in your
configuration. A server template is used to define the configuration
settings for a new application server. When you create a new
application server, you either select the default server template or a
template you previously created, that is based on another, already
existing application server. The default template is used if you do
not specify a different template when you create the server.
You could create a template from your initial profile and create a new profile using the template.
I believe that createAppServerTemplate creates e template for the server not the profile. Therefore if you already have configured a profile you can than use the template to create additional servers within this profile.
You would then use createApplicationServer to create new servers based on the above created template.
I guess if you want to copy a profile the best method is to record the configurations and set them in a script file.
Just for information In MyEclipseBlue version 10 we can export server profile configuration & import in new profile; hence retaining all the configuration.
René answer is correct but i faced issues while Running the server in Debug Mode.
\WebSphere8552\AppServer\properties\fsdb\AppSrv01.bat change was_user_script path
\WebSphere8552\AppServer\properties\fsdb_was_profile_defauldefault.bat change was_user_script path with actual
Also change path in : \AppServer\properties\profileRegistry.xml for validating license

Resources