I am working on SharePoint. I have two sites one main site and a sandbox. Their codes are same but xml names of columns are different. So I am trying to make a code in such a all xml names will be replaced by their variables.plzz check my code below.
#if TestSite
public const string context = "url";
public const string Title = "xmlname1";
public const string User_id = "xmlname2";
#else
public const string context = "url2";
public const string Title = "xmlname1";
public const string User_id = "xmlname2";
#endif
when I debug this program it connects to url1....how will I connect it to url2?
Both urls should work for Common code.
It is better to put some kind of identifier in the settings of your program. Then the user can set whether to connect to site A or B.
Sometimes you can use the URL to determine to which system you are connecting, or maybe you can even get the metadata from the service itself, removing the need to keep record of the column names to get. Then you first fetch the metadata, and then actually make the calls to the data endpoints.
Related
I have a problem, so I thought I would come to the brightest minds on the web.
I have written an ASP.NET MVC application that interfaces with a web service provided by another application. My app basically just adds some features to the other web application.
Both applications have a database. I am trying to limit the configuration for my application by using the other applications SQL Server credentials. This is so that if they decide to change the password for the other application, mine will just start working.
These credentials are saved in a .DSN file that my application can reach. How can I get my application, which uses Entity Framework, to use a connection string that is created from the details read in the .DSN file?
I can figure out the code to read the .DSN file, so if you wish to provide some code examples you can base them around setting the connection string for EF.
I am also open to other solutions, or even reasons why I shouldn't do this.
Thanks in advance.
PS. As I was writing this, I came up with a little concept. I am going to test it out now to see how it goes. But here is the basics:
On start up, read the needed details into static properties.
public MyContext() : base(getConnectionString()) { }
3.
private SomeObjectTypeHere getConnectionString()
{
//read static properties
//return .....something..... not sure yet....
}
Thoughts on that maybe?
EDIT
I have created a method that reads the .DSN file and gets the server, the user id and the password. I now have these stored in static properties. In my context, how can I set my connection string now that i have the required details.
So, the biggest issue that I was really having was how to set my connection string in Entity Framework. But I was also hoping that maybe someone else had worked with .DSN files.
Anyway, here was my solution. Still looking for problems that might arise from this, so if you can see any issues, let me know!
First, I created a method that was run on startup. This method ran through the .DSN file and picked out the gems.
Keep in mind that I have never worked with .DSN files, and the section that gets the password is unique to my situation.
var DSNFileContents = File.ReadAllLines(WebConfigurationManager.AppSettings["AppPath"] + #"\App.DSN");//reads DSN into a string array
//get UID
string uid = DSNFileContents.Where(line => line.StartsWith("UID")).First().Substring(4);//get UID from array
//test if uid has quotes around it
if (uid[0] == '"' && uid[uid.Length - 1] == '"')
{
//if to starts with a quote AND ends with a quote, remove the quotes at both ends
uid = uid.Substring(1, uid.Length - 2);
}
//get server
string server = DSNFileContents.Where(line => line.StartsWith("SERVER")).First().Substring(7);//get the server from the array
//test if server has quotes around it
if (server[0] == '"' && server[server.Length - 1] == '"')
{
//if to starts with a quote AND ends with a quote, remove the quotes at both ends
server = server.Substring(1, server.Length - 2);
}
//THIS WON'T WORK 100% FOR ANYONE ELSE. WILL NEED TO BE ADAPTED
//test if PWD is encoded
string password = "";
if (DSNFileContents.Where(line => line.StartsWith("PWD")).First().StartsWith("PWD=/Crypto:"))
{
string secretkey = "<secret>";
string IV = "<alsoSecret>";
byte[] encoded = Convert.FromBase64String(DSNFileContents.Where(line => line.StartsWith("PWD")).First().Substring(12));
//THIS LINE IN PARTICULAR WILL NOT WORK AS DecodeSQLPassword is a private method I wrote to break the other applications encryption
password = DecodeSQLPassword(encoded, secretkey, IV);
}
else
{
//password was not encrypted
password = DSNFileContents.Where(line => line.StartsWith("PWD")).First().Substring(4);
}
//build connection string
SqlConnectionStringBuilder cString = new SqlConnectionStringBuilder();
cString.UserID = uid;
cString.Password = password;
cString.InitialCatalog = "mydatabase";
cString.DataSource = server;
cString.ConnectTimeout = 30;
//statProps is a static class that I have created to hold some variables that are used globally so that I don't have to I/O too much.
statProps.ConnectionString = cString.ConnectionString;
Now that I have the connection string saved, I just have my database Context use it as below,
public class myContext : DbContext
{
public myContext() : base(statProps.ConnectionString) { }
//all my DbSets e.g.
public DbSet<Person> Persons{ get; set; }
}
This is simple, yes, but I hoping that it can provide some information to anyone that was looking to do something similar but was not sure about how it should be handled.
Again, let me know if you like or dislike this solution and if you dislike it, what is your solution and why.
Thanks again!
I have a class and am setting a UID as a class property because it is used in many methods throughout the program and I don't want to keep having to pass in a value to it. The issue I'm getting is that when I run context.Response.Write(uid) and refresh the page, I get the same value every time.
If I move createRandomString() to context.Response.Write(createRandomString()), I get a new UID every time I reload.
I'm very new to using C# and coming from a PHP background, this is a bit odd for me. I would think that setting a class property would change every load. I'm thinking it probably has something to do with when the program is compiled, the UID is permanently set which still wouldn't make sense.
Code where property is getting set:
public class Emailer : IHttpHandler {
// Define UID
static string uid = createRandomString();
CreateRandomString Code:
public static string createRandomString() {
Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");
return GuidString;
}
Static fields are only instansiated once. That is why you always get the same result. Try this...
public class Emailer : IHttpHandler
{
// Define UID
string uid => createRandomString();
}
https://msdn.microsoft.com/en-us/library/aa645751(v=vs.71).aspx
Static class level members with an initialiser are only once the first time any memeber of the class (static or otherwise) is referenced.
The initialisation will only re-run when the assembly the class is contained in is unloaded from memory (e.g. when then executable is unloaded).
For an ASP application the assemblies are loaded and unloaded by the IIS process so you would fund that if you restarted the IIS process (for example) this would cause a new UID to be generated.
Solved it by keeping the fields static but setting the value upon load.
Fields:
// Define UID
static string uid = "";
// Define upload path for files
static string uploadPath = "";
Setting:
// Define UID
uid = createRandomString();
uploadPath = #"c:\" + uid + #"\";
I had written a web performance test which was earlier working fine. Developers now have added a CSRF token validation (to prevent CSRF attack on the website). After this the test has started to fail (Error, Bad Request). I dug into it and found that the server is generating an XSRF-TOKEN on login request which has to be passed in every request there after.
Now to extract the token we need to parse response to the login request. How can we do it?
My coded tests looks like this:
WebTestRequest request4 = new WebTestRequest("https://servertest:8080/WebConsole/Account/Login");
request4.Method = "POST";
request4.Headers.Add(new WebTestRequestHeader("Accept", "application/json, text/plain, */*"));
request4.Headers.Add(new WebTestRequestHeader("Referer", "https://servertest:8080/WebConsole/index.html#/"));
StringHttpBody request4Body = new StringHttpBody();
request4Body.ContentType = "application/json;charset=utf-8";
request4Body.InsertByteOrderMark = false;
request4Body.BodyString = "{\"UserName\":\"pkdomain\\\\administrator\",\"Password\":\"sqa#123\"}";
request4.Body = request4Body;
yield return request4;
request4 = null;
WebTestRequest request5 = new WebTestRequest("https://servertest:8080/WebConsole/scripts/home/Pages/home-view.html");
request5.ThinkTime = 4;
request5.Headers.Add(new WebTestRequestHeader("Accept", "text/html"));
request5.Headers.Add(new WebTestRequestHeader("Referer", "https://servertest:8080/WebConsole/index.html#/"));
yield return request5;
request5 = null;
I believe the XSRF-TOKEN is returned in a cookie. Assuming that this is true in your case then the Set-Cookie header field contains the value and the required cookie must be extracted from it and saved to a context parameter. Subsequently that context parameter can be used wherever needed.
I suggest you create a sandbox .webtest file, do the steps below then convert it to coded test and copy the useful lines into the real test.
In more detail the steps are:
Add an Extract HTTP Header extraction rule for the Set-Cookie header field to the request that returns the XSRF-TOKEN value. Save the extracted value to a context parameter of your choice, give its name in one of the properties of the extraction rule; see the image below.
Add a call of the plugin below to the first request after the one with the above extraction rule. It extracts the required field from the cookie header field. The image below shows setting the properties of the call. (You might change the plugin to be a PostRequest and add it to the same request as the one with the extraction rule.)
public class ExtractCookieField : WebTestRequestPlugin
{
public string AllCookiesCP { get; set; }
public string FieldWantedCP { get; set; }
public string SavedFieldCP { get; set; }
// Expected to be called with AllCookiesCP containing text similar to:
// SomeHeader=639025785406236250; path=/; XSRF-TOKEN=somestring; secure; HttpOnly
public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e)
{
string AllCookiesText = e.WebTest.Context[AllCookiesCP].ToString();
foreach (string nameValuePair in AllCookiesText.Split(';'))
{
string[] nameAndValue = nameValuePair.Split(new char[] { '=' }, 2);
if (nameAndValue[0].Trim() == FieldWantedCP)
{
string sessionTokenId = nameAndValue[1].Trim();
e.WebTest.Context[SavedFieldCP] = sessionTokenId;
e.WebTest.AddCommentToResult(string.Format("Setting {{{0}}} to '{1}'", SavedFieldCP, sessionTokenId));
return;
}
}
// Dropping out of the loop means that the field was not found.
throw new WebTestException(string.Format("Cannot extract cookie field '{0}' from '{1}'", FieldWantedCP, AllCookiesText));
}
}
The value of the XSRF-TOKEN should now be in the context parameter specified in the SavedFieldCP property of the plugin call.
This image shows the add extraction rule dialogue and setting the context parameter where the extracted header field is saved, ie into CookieValues. It also show the add plugin and setting the three properties. After the plugin runs, assuming it is successful, the token value should be saved into the context parameter XsrfToken. The parameter values can be modified in the .webtest file via the properties panels of the extraction rule and the plugin. The values should also be clearly seen as simple variables and strings in a coded webb test.
I have this enum:
public enum PerfilUsuarioEnum
{
AdministradorSistema = 1,
AdministradorLoja = 2,
Gerente = 3
}
And I want to pass it on my Authorize roles
[Authorize(Roles = PerfilUsuarioEnum.AdministradorLoja + ", " + PerfilUsuarioEnum.Gerente)]
There is some manner to do this?
Roles has to be constant expression such as string. Easiest way is to use cosntant.
public static class PerfilUsuario
{
public const string AdministradorLoja = "AdministradorLoja";
public const string Gerente = "NaviGerentegators";
}
[Authorize(Roles = PerfilUsuario.AdministradorLoja + ", " +
PerfilUsuario.Gerente)]
Great question. Here is what I did...
I decided to make my permissions database driven so I needed a way to convert strings into something "typed" so that I could get compile time warnings and also so I could change the name of the permission in the database and not have to update all of our production code. Since the attributes are string based (so called magic strings), I decided against enumerations and went with a T4 script that read the database and generated a struct for each record. This allowed me to also add things like, a nice display name, details about the permission, and an error message that I could show the user.
Here is a sample permission row after the T4 template runs.
public struct CanViewClaimData
{
// Using const allows the compiler to generate the values in the assembly at compile time and satisfy MVC Authorize Attribute requirements for const strings.
public const System.String Name = "CanViewClaimData";
public const System.String DisplayName = "Can View Claim Data";
public const System.String Description = "The allows users to view claim data";
public const System.String DefaultErrorMessage = "You must have the \"Can View Claim Data\" permission to access this feature.";
}
Then in code I use a sub classed Authorize and mark the Action as such,
[Security.AuthorizedAttribute(Roles = CanViewClaimData.Name, Message = CanViewClaimData.DefaultErrorMessage)]
Then during each automated build and push to our C.I. environment, I run the T4 template as part of the build process to keep the struct strings in sync with the database.
So far this has worked really well and allowed me to give our product owner the ability to edit the permission names, descriptions etc, in the database and without a developer having to be involved.
i am working on a dashboard page where user will have a multiple choices to select properties and based on the selected properties it will generatea final URL and render.
so let say i have 10 different proprites:
ShowImage=true/false
ShowWindow=true/false
ShowAdmin = true/false
ShowAccounts = true/false
.............
..........
...........
my URL will be static which will be hitting the produciton so there is no change in terms of HOSTNAME.
so here is what i come-up with:
const string URL = "http://www.hostname.com/cont.aspx?id={0}&link={1}&link={2}........";
string.Format(URL, "123","aaa123", "123"............);
but the problem with the above solution is that, regardless it will generate me a long url whether i select or not...
any optimized solution?
You could use the StringBuilder class (System.Text namespace):
StringBuilder sbUrl = new StringBuilder();
sbUrl.AppendFormat("http://www.hostname.com/cont.aspx?id={0}", 123);
if (ShowImage) {
sbUrl.AppendFormat("&link1={0}", "aaa123");
}
if (ShowWindow) {
sbUrl.AppendFormat("&link2={0}", "aaa123");
}
string url = sbUrl.ToString();