Modified Web.Config using visual studio or powershell to specific web application - asp.net-mvc

I have a problem in modifying web.config to specific web application
I've search and try so many solution, when i deploy, the modification still affect to all existing web application
here is my code part of my code :
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWebService service = SPWebService.ContentService;
SPWebConfigModification myModification = new SPWebConfigModification();
SPSite site = new SPSite("http://win-a52s8epvot4:888/");
SPWeb web = site.OpenWeb();
myModification.Path = "configuration/appSettings";
myModification.Name = "add[#key='SQLArchiveConnectionString'][#value='Data Source=WIN-A52S8EPVOT4;Initial Catalog=TRAEmployee;User ID=sa;Password=P#ssw0rd;Persist Security Info=False;']";
myModification.Sequence = 0;
myModification.Owner = "administrator";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<add key='SQLArchiveConnectionString' value='Data Source=WIN-A52S8EPVOT4;Initial Catalog=TRAEmployee;User ID=sa;Password=P#ssw0rd;Persist Security Info=False;' />";
web.Site.WebApplication.WebConfigModifications.Add(myModification);
service.Update();
service.ApplyWebConfigModifications();
}
is there any suggestion for my problem
your reply will greatly help me to finish this problem
Regards,
Jay

Related

why asp.net mvc does not include the image uploaded folder in the project?

what I have found that the images uploaded by my application are not included in the project and that I have to include them manually image by image so what is the correct way of asp.net mvc project to let the images uploaded to be included in the project.
The following code is the one that upload the images to the folder and creates a unique name for each image. but still those images are not included in the project explorer.
public ActionResult Create(Job job, HttpPostedFileBase JobImage)
{
var value = "999999999";
var result4 = from app in db.Job where app.UniqueJobImageName.Contains(value) select app;
if(result4.FirstOrDefault() != null)
{
value = generateRandom();
}
if (ModelState.IsValid && CheckFileType(JobImage.FileName))
{
string ext = Path.GetExtension(JobImage.FileName);
var fileName = Path.GetFileName(JobImage.FileName);
job.JobImage = JobImage.FileName;
job.UniqueJobImageName = value + ext;
var path = Path.Combine(Server.MapPath("~/Images"), value + ext);
JobImage.SaveAs(path);
job.UserId = User.Identity.GetUserId();
job.jobUrl = "";
job.Month = DateTime.Now.ToString("MMMM");
job.DateAndTime = DateTime.Now;
AllJobModel all = new AllJobModel
{
JobTitle = job.JobTitle,
JobDescription = job.JobDescription,
JobImage = job.JobImage,
UniqueJobImageName = job.UniqueJobImageName,
locationName = job.locationName,
minimumSalary = job.minimumSalary.ToString(),
maximumSalary = job.maximumSalary.ToString(),
jobUrl = job.jobUrl,
PostedDate = DateTime.Now.ToString("dd/MM/yyyy"),
UserId= User.Identity.GetUserId(),
};
db.AllJobModel.Add(all);
db.SaveChanges();
db.Job.Add(job);
db.SaveChanges();
return RedirectToAction("Index","Home");
}else if (!CheckFileType(JobImage.FileName))
{
}
return View(job);
}
enter image description here
This doesn't make any sense. The uploaded images are content created by the user. They are not a deployable component of the site (or, they shouldn't be anyway). They are user-generated content, not developer resources.
If you are looking to effectively migrate your data (i.e. copy database entries and other user-generated content such as image files) from one environment to another, then that is a separate task for which you can create a separate process and/or automated script. Don't confuse it with the job of uploading a new version of your application code.
P.S. Even if what you were asking for was a sensible goal, it's impossible anyway - the executable version of your code is not the same as the code you see in Visual Studio in your project. In a modern ASP.NET application the executable code is in a different folder (even when you're running in debug mode in Visual Studio) and it has no concept or knowledge of the original project it was compiled from, or where to find it, or how to interact with it.

Kentico 9 - Separate MVC Application - Document Attachment

I am trying to add an attachment to a document - I am running a separate MVC application - not part of the same solution as the Kentico admin site.
I am getting error site not found for my UserInfo.
public Models.PartnerUpdateModel NewPartnerUpdate(Models.PartnerUpdateModel partnerupdatemodel)
{
CMS.DocumentEngine.TreeNode newpartnerupdatetreenode = CMS.DocumentEngine.TreeNode.New(partnerupdatemodel.KenticoPartnerUpdate.ClassName);
TreeProvider tree = new TreeProvider();
partnerupdatemodel.KenticoPartnerUpdate.Title = partnerupdatemodel.Title;
partnerupdatemodel.KenticoPartnerUpdate.Summary = partnerupdatemodel.Summary;
partnerupdatemodel.KenticoPartnerUpdate.Article = partnerupdatemodel.Article;
partnerupdatemodel.KenticoPartnerUpdate.Author = partnerupdatemodel.MarketConnectUser.UserID.ToString();
partnerupdatemodel.KenticoPartnerUpdate.DocumentCulture = partnerupdatemodel.DocumentCulture;
partnerupdatemodel.KenticoPartnerUpdate.Insert(TreeHelper.SelectSingleNode(partnerupdatemodel.MarketConnectUser.DefaultGroup.GroupChildNodes.Where(x => x.Key == partnerupdatemodel.ParentClassName).Select(x => x.Value).Single()), true);
partnerupdatemodel.KenticoPartnerUpdate.SubmitChanges(true);
foreach (var file in partnerupdatemodel.Files)
{
HttpPostedFile postedfile = FileHelper.ConstructHttpPostedFile(FileHelper.ToByteArray(file.InputStream), file.FileName, file.ContentType);
DocumentHelper.AddAttachment(newpartnerupdatetreenode, Models.PartnerUpdateModel.AttachmentColumnNames.Image.ToString(), postedfile, new TreeProvider(MembershipContext.AuthenticatedUser)); //GETTING ERROR HERE
newpartnerupdatetreenode.Update();
}
return partnerupdatemodel;
}
MembershipContext is not oficially supported in v9 (Supported and unsupported Kentico features on MVC sites) however I think this should work - to be honest I have tried it by myself and I`ve got UserInfo (for public user and global admin too). Could you please provide call stack of exception?
edit: I have also tried to get current SiteInfo like
var site = SiteContext.CurrentSite;
and it`s null if you have not specified Presentation URL - could you check this setting?

Rotativa generating blank PDF in Server

We are using Rotativa in a .Net MVC 5 project. it works like a charm locally and fails (generates a blank PDF) equally when deployed to server. However, if I login to server and access the website as localhost it generates PDF just fine.
So it looked like a permission issue with which Application pool is running on. So, for testing purpose, I changed to run the App Pool to run on "Local System". Still same issue.
We have also tried:
"ViewasPDF"
App settings which looks like: <add key="WkhtmltopdfPath" value="<path to the folder>"/>
Below is the code:
return new ActionAsPdf("ActionMethod",new { id = id, partSelected = part, selectedTab = selectedTab, isDownload = true })
{
FileName = fileName,
PageMargins = { Left = 0, Right = 0 },
CustomSwitches = "--disable-external-links --disable-internal-links --disable-smart-shrinking --viewport-size 1600x900 --load-error-handling ignore",
PageOrientation = Rotativa.Options.Orientation.Portrait,
PageSize = Rotativa.Options.Size.A4,
PageWidth = 210,
PageHeight = 297
};
First, you have disabled displaying error with the custom switch --load-error-handling ignore. It might help to not have it disabled temporarily for the purpose of debugging.
Secondly, a blind guess from me is that you may have some images that require local path as src on the pdf? If that's the case you will need #Server.MapPath for each one of those.
For example:
<img src="#Server.MapPath("your image path")"/>
var iResult = new Rotativa.ActionAsPdf("PrintForm", new { Id = Id }) { FileName = iFilename, SaveOnServerPath = ViewBag.FileName };
iResult.UserName = System.Configuration.ConfigurationManager.AppSettings["ADUserID"].ToString();
iResult.Password = System.Configuration.ConfigurationManager.AppSettings["ADPassword"].ToString();
return iResult;
Here is a code example where aduser is user name and password, please create a generic user account for this..

Changing Android Apk Locale via Robotium

I'm working on an activity instrumentation test case which automates verification of an AUT using the Robotium framework. There are several language tests I want to automate. I've attempted to change language via Robotium by pulling the resources from the AUT and forcing the local locale configuration to a different language, but to no avail:
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = res.getConfiguration();
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
I've also heard that it used to be possible that one could change the language using ADB using the activity manager, but I've been unable to find a working solution for V4.2.2. Short of embedding code in the application itself or rooting the device, is there any way to change locale remotely, through Robotium or otherwise?
Thanks in advance
I had a similar problem some time ago and came to the following solution:
private void changeActivityLocale(final Activity a, String locale ){
Resources res = a.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = new Locale(locale);
res.updateConfiguration(conf, dm);
a.getResources().updateConfiguration(conf, dm);
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
a.recreate();
}
});
}
I call this method inside my test case before starting some locale specific tests.
Hope it helps you.
Best regards,
Peter
protected void changeLocale(Locale locale)
throws ClassNotFoundException, SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
NoSuchFieldException {
#SuppressWarnings("rawtypes")
Class amnClass = Class.forName("android.app.ActivityManagerNative");
Object amn = null;
Configuration config = null;
// amn = ActivityManagerNative.getDefault();
Method methodGetDefault = amnClass.getMethod("getDefault");
methodGetDefault.setAccessible(true);
amn = methodGetDefault.invoke(amnClass);
// config = amn.getConfiguration();
Method methodGetConfiguration = amnClass.getMethod("getConfiguration");
methodGetConfiguration.setAccessible(true);
config = (Configuration) methodGetConfiguration.invoke(amn);
// config.userSetLocale = true;
#SuppressWarnings("rawtypes")
Class configClass = config.getClass();
Field f = configClass.getField("userSetLocale");
f.setBoolean(config, true);
// set the locale to the new value
config.locale = locale;
// amn.updateConfiguration(config);
Method methodUpdateConfiguration = amnClass.getMethod(
"updateConfiguration", Configuration.class);
methodUpdateConfiguration.setAccessible(true);
methodUpdateConfiguration.invoke(amn, config);
}
You will need permission in your application:
android.permission.CHANGE_CONFIGURATION
for api level >= 17 you have to grant it via adb:
adb shell pm grant application_package android.permission.CHANGE_CONFIGURATION

how can i automate calling a url on a password protected asp.net-mvc site

i have an asp.net-mvc site with sqlserver backend and i am using membershipprovider for login, etc.
I have a few automated things that i want to run daily or weekly as i can do this today if i:
Log In
call URL
so lets say the URL is
www.mysite.com/MyController/RunCleanupScript
I know some people will suggest breaking the code of RunCleanupScript into a standalone script outside of the website but i wanted to see if there was a solution to automating the equivalent to the manual login and then entering in this url to call this script?
Phil Haak has a post about a solution which may work for you - he also warns of the dangers associated. You could use this method to schedule the clean up task. If you move your clean-up code out of the controller then there is no need for the login - it can never be called externally. If you need to still be able to login and force the clean up, then moving the clean up code out of your controller is still the way to go. Your secured action and the scheduler code will both call the clean-up code.
Another option could be to create a windows service that hits the action and stores the required credentials in its config file.
Forms auth together with some scripts calling web pages to aquire a cookie may not be the most stable and maintainable approach for your requirements.
You could support basic auth that makes passing username and password from a script easy. For an example how to implement basic auth in asp.net mvc see this blog post.
You could write a console application which will perform 2 HTTP requests: first to login and second to fetch the protected resource:
using System;
using System.Collections.Specialized;
using System.Net;
public class WebClientEx: WebClient
{
private readonly CookieContainer _cookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
((HttpWebRequest)request).CookieContainer = _cookieContainer;
return request;
}
}
class Program
{
static void Main()
{
using (var client = new WebClientEx())
{
var values = new NameValueCollection
{
{ "username", "user" },
{ "password", "pwd" },
};
// Login
client.UploadValues("http://example.com/account/logon", values);
// Fetch the protected resource
var result = client.DownloadString("http://example.com/home/foo");
Console.WriteLine(result);
}
}
}
This code will login to a FormsAuthentication site, then use the AUTH cookie to hit any other URL on the site...
string appURL = "https://.../LogOn";
// UserName and Password should match the names of the inputs on your form
string strPostData = String.Format("UserName={0}&Password={1}", "login", "pass");
Cookie authCookie;
CookieContainer cookieJar = new CookieContainer();
// Prepare post to the login form
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(appURL);
req.Method = "POST";
req.ContentLength = strPostData.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = cookieJar;
req.AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
// Proxy - Optional
// req.Proxy.Credentials = CredentialCache.DefaultCredentials;
// Post to the login form.
StreamWriter swRequestWriter = new StreamWriter(req.GetRequestStream());
swRequestWriter.Write(strPostData);
swRequestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)req.GetResponse();
// Store the required AUTH cookie
authCookie = cookieJar.GetCookies(new Uri("... your cookie uri ..."))[".ASPXAUTH"];
Now you can access any other URL of the site using the AUTH cookie.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("... url ...");
req.CookieContainer.Add(new System.Net.Cookie(authCookie.Name,
authCookie.Value,
authCookie.Path, "localhost"));
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
PowerShell might be a good option for you. Here's a sample that demonstrates how you would post form values to the log-on page and then use the response cookie to make a second call to the admin page.
Note, I borrowed much of this sample from this post.
$LogonUrl = "http://yoursite.com/Account/LogOn"
$UserName = "AdminUser"
$Password = "pass#word1"
$AdminUrl = "http://yoursite.com/MyController/RunCleanupScript"
$cookies = New-Object System.Net.CookieContainer
$formData = "UserName=" + $UserName + "&Password=" + $Password
[net.httpWebRequest] $web1 = [net.webRequest]::create($LogonUrl)
$web1.method = "POST"
$web1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
$web1.Headers.Add("Accept-Language: en-US")
$web1.Headers.Add("Accept-Encoding: gzip,deflate")
$web1.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
$web1.AllowAutoRedirect = $false
$web1.ContentType = "application/x-www-form-urlencoded"
$buffer = [text.encoding]::ascii.getbytes($formData)
$web1.ContentLength = $buffer.length
$web1.TimeOut = 50000
$web1.KeepAlive = $true
$web1.Headers.Add("Keep-Alive: 300");
$web1.CookieContainer = $CookieContainer
$reqStrm = $web1.getRequestStream()
$reqStrm.write($buffer, 0, $buffer.length)
$reqStrm.flush()
$reqStrm.close()
[net.httpWebResponse] $response = $web1.getResponse()
$respStrm = $response.getResponseStream()
$reader = new-object IO.StreamReader($respStrm)
$result = $reader.ReadToEnd()
$response.close()
$web2 = new-object net.webclient
$web2.Headers.add("Cookie", $response.Headers["Set-Cookie"])
$result = $web2.DownloadString("$AdminUrl")
Write-Output $result
This could also easily be turned into a Windows Console app as well. Either way, they are easy to schedule with Task Scheduler.
Hope this helps.
Why don't you give WatiN or Selenium a try? You can set up a login step very easy and then test if the other RunCleanupScript page is working properly.
WatiN's main page example:
[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}
You can then have something like:
[Test]
public void TestRunCleanupScript()
{
using (var browser = new IE("www.mysite.com/MyController/RunCleanupScript"))
{
DoLogin(browser)
//navigate to cleanupscript page
//your assert
}
}
public void DoLogin(browser)
{
//navigate to login
//type username and password and hit button
}
I am currently doing this in a production environment. In my case the solution was a no-brainer since MADAM had already been installed in order to allow normal RSS Readers to securely access RSS feeds on the site.
The trick to doing this is to enable Basic Authentication for the pages you want to call automatically using any external processes, that opens you up to a huge number of ways to access the site automatically; this VBScript file, for instance calls the maintenance URL and checks whether the response from the server is exactly SUCCESS.
Option Explicit
Dim result
result = PerformMaintenance("http://www.mysite.com/MyController/RunCleanupScript")
WScript.Quit(result)
Function PerformMaintenance(URL)
Dim objRequest
Set objRequest = CreateObject("Microsoft.XmlHttp")
'I use a POST request because strictly speaking a GET shouldn't change anything on the server.
objRequest.open "POST", URL, false, "LimitedDaemonUser", "SecretDaemonPassword"
objRequest.Send
if (objRequest.ResponseText = "SUCCESS") Then
PerformMaintenance = 0
Else
PerformMaintenance = 1
End If
set objRequest = Nothing
End Function
Basic Authentication is easy enough to get working. Just include MADAM with your project, and configure it in your Web.config.
Adding these Web.config sections/parameters (IIS6) should get your example request working if you use a standard MembershipProvider. You just have to change MyNamespace.MembershipUserSecurityAuthority to a reference to an actual class. The source code for MembershipUserSecurityAuthority is included with MADAM in the demo web application's App_Code folder.
<configuration>
<configSections>
<sectionGroup name="madam">
<section name="userSecurityAuthority" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="formsAuthenticationDisposition" type="Madam.FormsAuthenticationDispositionSectionHandler, Madam" />
</sectionGroup>
</configSections>
<madam>
<userSecurityAuthority realm="MyRealm" provider="MyNamespace.MembershipUserSecurityAuthority, MyNamespace" />
<formsAuthenticationDisposition>
<discriminators all="false">
<discriminator inputExpression="Request.AppRelativeCurrentExecutionFilePath" pattern="~/MyController/RunCleanupScript$" type="Madam.RegexDiscriminator, Madam" />
</discriminators>
</formsAuthenticationDisposition>
</madam>
<system.web>
<httpModules>
<add name="FormsAuthenticationDisposition" type="Madam.FormsAuthenticationDispositionModule, Madam" />
<add name="AuthenticationModule" type="Madam.BasicAuthenticationModule, Madam" />
</httpModules>
</system.web>
</configuration>

Resources