Can any one let me know how to get a bool result, verifying a value exists in a web.config's key.
Scenario is,
I have this tag in my website...
<add key="isEnabled" value="False"/> for a website,
On this key value I keep my site 'on' and 'off' using
public static bool isEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["isEnabled "]);
if(isEnabled)
{
//
}
now the requirement is got 3-4 websites now, want to change the above line to something like
<add key="SitesEnabled" value="1,4,5"/>
because i want to enable only 1st, 4th, 5th site
1 - is the static value for my 1st website, 2 - 2nd.....
But now how do I do on and off...my websites something like
public static bool OneSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="1"]); // true
public static bool TwoSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="2"]); //false
Please let me know ...Thanks
I would do it something like this:
using System.Linq;
var sitesEnabled =
ConfigurationManager.AppSettings["SitesEnabled"] != null
? ConfigurationManager.AppSettings["SitesEnabled"].Split(',')
: new string[0];
var oneSiteEnabled = sitesEnabled.Contains("1");
var twoSiteEnabled = sitesEnabled.Contains("2");
Related
Can't find a code sample for this in any of the documentation. Using MudTable ServerData feature, want to store the tables state (page no, page size, sorting) into the url as it changes which Iv'e done:
NavigationManager.NavigateTo($"/list/MyEntity/?PageNo={state.Page}&PageSize={state.PageSize}&SortLabel={state.SortLabel}&SortDirection={(state.SortDirection == MudBlazor.SortDirection.Ascending ? "asc" : "desc")}&Filter={Filter}", false);
However on loading the page, I want to push these parameters into the MudTable
table.CurrentPage = PageNo;
table.RowsPerPage = PageSize;
await table.ReloadServerData();
however I get warnings that I can't use 'table.CurrentPage' outside of component. Any way to implement what I want in current version of MudTable?
Assigning the values to component parameters in code is not the Blazor way. All you need to do is to set them in Razor like this:
<MudTable Items="#Elements" CurrentPage="PageNo" RowsPerPage="PageSize">
...
<PagerContent>
<MudTablePager />
</PagerContent>
</MudTable>
Here is a fiddle to play around with live. It shows that setting the two parameters in razor works. https://try.mudblazor.com/snippet/QaQlvFvLmZkKlaWQ
I think this should do the trick. Sadly, NavigateTo() looks broken.
#inject NavigationManager NavigationManager
<MudTable
#* ... *#
</MudTable>
#code
{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// on first render, _table is null
if (firstRender)
{
return;
}
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
var queryComponents = QueryHelpers.ParseQuery(uri.Query);
queryComponents.TryGetValue("PageNo", out StringValues pageNo);
queryComponents.TryGetValue("PageSize", out StringValues pageSize);
int rowsPerPage = int.Parse(pageSize.First());
int page = int.Parse(pageNo.First());
_table.SetRowsPerPage(rowsPerPage);
//_table.NavigateTo(page); // this is broken
await _table.ReloadServerData();
}
}
Has anyone used Sage Pay with asp.net Webpages??
I have downloaded the integration kit from Sage Pay but this is made in webforms and i am having trouble converting it the WebPages format.
Sage Pay are no help so i'm hoping someone out there has done this. Or can point me in the right direction.
I have managed to do this using the class from the SagePay template you can download.
Put these files in your bin folder:-
SagePay.IntegrationKit.DotNet.dll
SagePay.IntegrationKit.DotNet.pdb
Put these files in your App_Code folder:-
SagePayConfiguration.cs
SagePayAPIIntegration.cs
SagePayFormIntegration.cs
You also need to add some stuff to your web.config file
<SagePayConfiguration>
<!--Mandatory
Set to TEST for the Test Server and LIVE for the live environment-->
<add key="sagepay.api.env" value="TEST" />
<!--Transaction Settings -->
<add key="sagepay.api.protocolVersion" value="3.00" />
<add key="sagepay.kit.vendorName" value="your Name" />
<add key="sagepay.kit.fullUrl" value="your url" />
<add key="sagepay.kit.currency" value="GBP" />
<!--Optional setting. It's recommended to set the siteFqdn value to the Fully
Qualified Domain Name of your server.
This should start http:// or https:// and should be the name by which our servers can call back to yours
i.e. it MUST be resolvable externally, and have access granted to the Sage Pay servers
examples would be https://yoursite or http://212.111.32.22/
NOTE: Do not include any URI path.
If you leave this value blank the kit will use the current host name-->
<add key="sagepay.kit.siteFqdn.LIVE" value="http://your web address" />
<add key="sagepay.kit.siteFqdn.TEST" value="http://your web address" />
<!--Mandatory. Usually PAYMENT. This can be DEFERRED or AUTHENTICATE if your Sage Pay
account supports those payment types
NB Ideally all DEFERRED transaction should be released within 6 days (according to card scheme rules).
DEFERRED transactions can be ABORTed before a RELEASE if necessary-->
<add key="sagepay.kit.defaultTransactionType" value="PAYMENT" />
<!--0 = If AVS/CV2 enabled then check them. If rules apply, use rules (default).
1 = Force AVS/CV2 checks even if not enabled for the account. If rules apply, use rules.
2 = Force NO AVS/CV2 checks even if enabled on account.
3 = Force AVS/CV2 checks even if not enabled for the account but DON'T apply any rules.-->
<add key="sagepay.kit.applyAvsCv2" value="0" />
<!--0 = If 3D-Secure checks are possible and rules allow, perform the checks and apply the authorisation rules. (default)
1 = Force 3D-Secure checks for this transaction if possible and apply rules for authorisation.
2 = Do not perform 3D-Secure checks for this transaction and always authorise.
3 = Force 3D-Secure checks for this transaction if possible but ALWAYS obtain an auth code, irrespective of rule base.-->
<add key="sagepay.kit.apply3dSecure" value="0" />
<!--FORM Protocol Only Settings
Set this value to the Encryption password assigned to you by Sage Pay -->
<add key="sagepay.kit.form.encryptionPassword.TEST" value="Your password" />
<add key="sagepay.kit.form.encryptionPassword.LIVE" value="Your password" />
<!--The Sage Pay server URLs to which customers will be sent for payment for each environment-->
<add key="sagepay.api.formPaymentUrl.LIVE" value="https://live.sagepay.com/gateway/service/vspform-register.vsp" />
<add key="sagepay.api.formPaymentUrl.TEST" value="https://test.sagepay.com/gateway/service/vspform-register.vsp" />
</SagePayConfiguration>
To make this easier to manage i have but this web.config file in the checkout folder so it is easy to keep updated.
I also created the following class to encrypt and dencrypt the data:-
you can call it what ever you want but it needs to be saved in the App_Code folder.
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public static class EncryptionHelper
{
private static byte[] keyAndIvBytes;
static EncryptionHelper()
{
// You'll need a more secure way of storing this, I this isn't
// a real key
keyAndIvBytes = UTF8Encoding.UTF8.GetBytes("123123123123123b");
}
public static string ByteArrayToHexString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static string DecodeAndDecrypt(string cipherText)
{
string DecodeAndDecrypt = AesDecrypt(StringToByteArray(cipherText));
return (DecodeAndDecrypt);
}
public static string EncryptAndEncode(string plaintext)
{
return ByteArrayToHexString(AesEncrypt(plaintext));
}
public static string AesDecrypt(Byte[] inputBytes)
{
Byte[] outputBytes = inputBytes;
string plaintext = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(outputBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(cryptoStream))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
public static byte[] AesEncrypt(string inputText)
{
byte[] inputBytes = UTF8Encoding.UTF8.GetBytes(inputText);//AbHLlc5uLone0D1q
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateEncryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
private static RijndaelManaged GetCryptoAlgorithm()
{
RijndaelManaged algorithm = new RijndaelManaged();
//set the mode, padding and block size
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 128;
algorithm.BlockSize = 128;
return algorithm;
}
}
I call the the class like so:-
string crypt = "blahblahblah";
string EncryptAndEncode = EncryptionHelper.EncryptAndEncode(crypt);
string DecodeAndDecrypt = EncryptionHelper.DecodeAndDecrypt(EncryptAndEncode);
When the transaction is complete i get the crypt with this code:-
IFormPaymentResult PaymentStatusResult = new DataObject();
if (Request.QueryString["crypt"] != null && !string.IsNullOrEmpty(Request.QueryString["crypt"]))
{
SagePayFormIntegration sagePayFormIntegration = new SagePayFormIntegration();
PaymentStatusResult = sagePayFormIntegration.ProcessResult(Request.QueryString["crypt"]);
}
you can then call the needed information from the calss like so
if (PaymentStatusResult.Status == ResponseStatus.NOTAUTHED)
{reason = "You payment was declined by the bank. This could be due to insufficient funds, or incorrect card details.";}
You can see all the fields in the Result.aspx of the SagePay template.
i cant connect to sql 2012 in asp.net , c#
file: defalut.aspx -> page_Load
List<ozhatdata.tbl_diller> diller_result;
using (var ctx = new ozhatdata.bagDataContext())
{
diller_result = ozhatdata.DilIslemleri.GetAllLanguages(ctx);
}
int cnt = diller_result.Count ; // diller_result is null error
when i go to definition (F12) of the bagDataContext()
file: bag.designer.cs
public bagDataContext() :
base(global::ozhatdata.Properties.Settings.Default.ozhatprojeConnectionString15, mappingSource)
{
OnCreated();
}
when i go to definition (F12) of ozhatprojeConnectionString15
file: settings.designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute( "Data Source=.\\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;"+
"User ID=sa;Password=123; ")]
public string ozhatprojeConnectionString15 {
get {
return ((string)(this["ozhatprojeConnectionString15"]));
}
}
later i learned there is app.config file this line was present in app.config
<add name="Settings.ozhatprojeConnectionString15"
connectionString="Data Source=LIVE2RISE\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
i can connect to "user:sa pass:123" on "ms sql management studio"
!!!!error!!!!!!
System.NullReferenceException: Object reference not set to an instance of an object.
diller_result.count // this diller_result is null in debugger
line 36: for (int i = 0; i < diller_result.Count; i++)
Kaynak Dosya: c:\inetpub\wwwroot\site\Default.aspx.cs line : 36
im trying to figure out since yesterday.
please help me, thnks.
edit: after responce i tracked adn put a breakpoint
public static List<tbl_diller> GetAllLanguages(bagDataContext ctx = null)
{
try
{
//some stuf was here i deleted
}
catch (Exception ex)
{
string ms = ex.Message; // !!breakpoint
// the exception= coundt find stored procedure "dbo.getalllangs"
return null;
}
}
thank you. the problem is solved. it was caused by an evil try-cath duo.
i'll be more cautious with these "try catchs" from now on.
2nd time and Solution: this time eventhough i edit app.config, program uses old ConString from settings.designer.cs(i tracked it while debugging).
the program uses connString from setting.designer.cs too. app.config is not used/looked up/referred when Debugging
so we have to navigate in the solution>properties>settings.designer.cs edit connectionStrings there too.
i hope this helps anyone in future.
you can read this too:
Force regeneration of Settings.settings file after change in app.config
It seems that it is the call to ozhatdata.DilIslemleri.GetAllLanguagesthat did return a null value for diller_result.
You might want to check in that method what is causing it to return null.
I need to save a value for all my website, is there a way to save it in a global variable in the server side like ViewData for example or is it better to save it in a cookie ?
This data is set using a dropdown list and cached in the controller.
Thanks.
In the Global.asax page
void Application_Start(object sender, EventArgs e)
{
// set your variable here
Application["myVar"] = "some value";
}
Inside the action
public ActionResult MyAction()
{
// get value
string value = Application["myValue"].ToString();
// change value
Application["myValue"] = "some NEW value";
}
You could store it in the Application state:
public ActionResult Foo()
{
HttpContext.Application["someKey"] = "some value";
...
}
and then later read from it:
string value = (string)HttpContext.Application["someKey"];
The values stored in the Application state are shared among all users of the website.
If you need to store user specific data you could use session or cookies depending on whether it is sensitive data or not.
Session would be the way if you are wanting to change the value, if the value is going to be static & is known before the application loads any data then you could store it in the Web.config and reference it from there.
Such as:
<appSettings>
<add key="MyStaticItem" value="Lulz" />
</appSettings>
So then if you want to retreive that string you can do:
Meh = ConfigurationManager.AppSettings["MyStaticItem"]
Meh would be Lulz
Can also use session like this:
Session["MyKey"] = "MyValue";
and retrieving like this:
var myVar = (string)Session["MyKey"];
if that's per user value.
Hope this is of help.
Is there a way of listing which roles have access to a given page via code?
Example, I have a Testpage.aspx, and I wanted to list the roles allowed for this page when a user accesses the page. The URLAuthorizationManager must be able to find this out somehow, so there must be a way it knows what roles are configured in the webconfig for a page. or URL.
Here is the webconfig limiting the roles allowed to view this page.
<location path="Testpage.aspx">
<system.web>
<authorization>
<allow roles ="admin,sales" />
</authorization>
</system.web>
</location>
If I could find a solution, it would return "admin", "sales". Any one know how I can do this? Thanks
You can use the following code inside the page where you want to obtain the information.
var section = (AuthorizationSection)
WebConfigurationManager.GetSection("system.web/authorization");
var rules = section.Rules;
var allowedRoles = rules
.OfType<AuthorizationRule>()
.Where(r => r.Action == AuthorizationRuleAction.Allow)
.Select(r => r.Roles).First();
The reason for the call to First() is that .NET configuration is hierarchical. Suppose you have the following web site hierarchy and configuration:
/Default.aspx
/Web.config (<allow roles="admin,user" />)
/SubDir/
/Test.aspx
/Web.config (<allow roles="admin,other" />)
and you call the code above from Test.aspx.cs, then the property AuthorizationSection.Rules contains three items corresponding to respectively the configuration from /SubDir/Web.config, Web.config and machine.config. So the first element contains the roles admin and other.
My problem was very similar except I needed the ability to iterate through all of the
directories and related subdirectories and display allowed roles for each web page and folder directory. I was unable to use Ronald Wildenberg's solution because we're using .Net 2.0 so we don't have the Linq functionality.
His solution gave me the roadmap I needed. I also found help from from Microsoft's French IIS Support Team, Managing Forms Authentication Programmatically. I didn't want to rewrite the config files like they posted, rather we needed the ability to show the allowed roles for all directories and pages in our application. Our application is small. It has a total of 15 directories and less than 100 pages so this runs pretty quickly. Your mileage my vary depending on the size of your web site.
I started from the root directory and recursively searched for all webconfigs. I added them with their path to a string list then iterated through the list and called my ListRoles function. This function opens the web config and gets the location collection. Then it looks for the "system.web/authorization" like Ronald did. If it finds an authorization section it loops through the rules and excludes any inherited rules and focuses on AuthorizationRuleAction.Allow with associated roles:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
public void DisplayWebPageRoles()
{
//First walk the directories and find folders with Web.config files.
//Start at the root
DirectoryInfo baseDir = new DirectoryInfo(Server.MapPath("~/"));
//Do a little recursion to find Web.Configs search directory and subdirs
List<string> dirs = DirectoriesWithWebConfigFile(baseDir);
//Replace the folder path separator except for the baseDir
for (int i = 0; i < dirs.Count; i++)
{
dirs[i] = dirs[i].Replace(
baseDir.FullName.Replace("\\", "/"),
"/" + baseDir.Name + (i > 0 ? "/" : ""));
}
//Now that we have the directories, we open the Web.configs we
//found and find allowed roles for locations and web pages.
for (int i = 0; i < dirs.Count; i++)
{
//Display on page, save to DB, etc...
ListRoles(dirs[i]);
}
}
public List<string> DirectoriesWithWebConfigFile(DirectoryInfo directory)
{
List<string> dirs = new List<string>();
foreach (FileInfo file in directory.GetFiles("Web.config"))
{
dirs.Add(directory.FullName.Replace("\\","/"));
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dirs.AddRange(DirectoriesWithWebConfigFile(dir));
}
return dirs;
}
private void ListRoles(string configFilePath)
{
System.Configuration.Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(configFilePath);
//Get location entries in web.config file
ConfigurationLocationCollection locCollection = configuration.Locations;
string locPath = string.Empty;
foreach (ConfigurationLocation loc in locCollection)
{
try
{
Configuration config = loc.OpenConfiguration();
//Get the location path so we know if the allowed roles are
//assigned to a folder location or a web page.
locPath = loc.Path;
if (locPath.EndsWith(".js")) //Exclude Javascript libraries
{
continue;
}
AuthorizationSection authSection =
(AuthorizationSection)config
.GetSection("system.web/authorization");
if (authSection != null)
{
foreach (AuthorizationRule ar in authSection.Rules)
{
if (IsRuleInherited(ar))
{
continue;
}
if (ar.Action == AuthorizationRuleAction.Allow
&& ar.Roles != null
&& ar.Roles.Count > 0)
{
for (int x = 0; x < ar.Roles.Count; x++)
{
//Display on page, save to DB, etc...
//Testing
//Response.Write(
// configFilePath + "/web.config" + ","
// + configFilePath + "/" + locPath + ","
// + ar.Roles[x] + "<br />");
}
}
}
}
}
catch (Exception ex)
{
//Your Error Handling Code...
}
}
}
From French IIS support Team blog
private bool IsRuleInherited(AuthorizationRule rule)
{
//to see if an access rule is inherited from the web.config above
//the current one in the hierarchy, we look at two PropertyInformation
//objects - one corresponding to roles and one corresponding to
//users
PropertyInformation usersProperty = rule.ElementInformation.Properties["users"];
PropertyInformation rolesProperty = rule.ElementInformation.Properties["roles"];
//only one of these properties will be non null. If the property
//is equal to PropertyValueOrigin.Inherited, the this access rule
//if not returned in this web.config
if (usersProperty != null)
{
if (usersProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
if (rolesProperty != null)
{
if (rolesProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
return false;
}
Use the Roles.GetAllRoles() method
http://msdn.microsoft.com/en-us/library/system.web.security.roles.getallroles.aspx
and here is an example where they list all roles:
http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx