So I am trying to get the list of the items that I have to deliver based off of orders between certain dates from paypal. I couldn't find any solution or explanation on paypal developer documentation on this.
So I use "paypal here" to receive POS payments for orders during the week. I wanted to essentially get an order list if you will (I was surprised that paypal didn't offer an api call for this). By order list I mean a list of customers and each customer's list of items(shopping cart) that they have ordered. I believe "paypal here" treats all orders as an invoice.
So after a lot of research, I got a list of invoices from the api. However, none of the invoices include the shopping cart information (the items they have ordered.). I would greatly appreciate any suggestions or help.
Config file --->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>-->
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="live" />
<add name="clientId" value=" client id" />
<add name="clientSecret" value="client Secret" />
</settings>
</paypal>
</configuration>
C# Code --->
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PayPal.Api;
namespace PaypalConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var test = Invoice.GetAll(apiContext, pageSize: 10, totalCountRequired: true);
}
}
}
Update:
Link to SDK--> https://github.com/paypal/PayPal-NET-SDK
Related
I want to verify user payment whether its authentic or not. I am getting response from pay pal but i want to resend that response to pay pal to verify it. I am getting all the details regarding payments and user.
You can verify your by using pay pal api.
First install payPal from nuget packages
Install-Package PayPal
Secondly configure your webconfig like this.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<configuration>
<paypal>
<settings>
<add name="mode" value="sandbox"/>
<add name="clientId" value="client_id"/>
<add name="clientSecret" value="client_secret_id"/>
</settings>
</paypal>
</configuration>
Then from server side i mean C# end you can verify your payment like this.
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
// --verify payment ---
var payment = Payment.Get(apiContext, "PAY-YourCheckNo");
Here payment variable will populate with different status defending upon your pay-yourcheckNo. This is how you can verify your payment done through paypal.
I'd like to take advantage of the new Windows Azure Cache Service (Preview) and was able to successfully store in and retrieve things from the cache using Session by following this article. Unfortunately we are storing Linq to Sql objects in Session and we are not able to change that at this point. When attempting to store such objects in Session using the Azure Cache Service, I get the following error:
Type 'System.Data.Linq.EntitySet`1[cachetest.Child]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.
I used the "Unidirectional" Serialization Mode for my data context, so all declarations are already decorated with "DataContract" and "DataMember" attributes (see code sample below).
I've looked into using a Custom Serializer similar to this article and this article on stackoverflow, but received an error that matched the exact error described towards the end of this article, in which it is stated that
the ASP.NET providers for Cache do not support binary or custom serialization types
Since a custom serializer is not an option, how else can I store Linq to Sql objects (with parent-child relationships) in Session using Windows Azure Caching?
I've broken out the code that illustrates the issue below.
The Linq DataContext:
<?xml version="1.0" encoding="utf-8"?><Database Class="TestModelDataContext" Serialization="Unidirectional" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
<Table Name="" Member="Parents">
<Type Name="Parent">
<Column Member="Name" Type="System.String" CanBeNull="false" />
<Column Member="ParentId" Type="System.Int32" IsPrimaryKey="true" CanBeNull="false" />
<Association Name="Parent_Child" Member="Childs" ThisKey="ParentId" OtherKey="ParentId" Type="Child" />
</Type>
</Table>
<Table Name="" Member="Childs">
<Type Name="Child">
<Column Member="Name" Type="System.String" CanBeNull="false" />
<Column Member="ChildId" Type="System.Int32" IsPrimaryKey="true" CanBeNull="false" />
<Column Member="ParentId" Type="System.Int32" CanBeNull="false" />
<Association Name="Parent_Child" Member="Parent" ThisKey="ParentId" OtherKey="ParentId" Type="Parent" IsForeignKey="true" />
</Type>
</Table>
</Database>
Page using the session:
namespace cachetest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Parent newParent = new Parent { Name = "John", ParentId=1 };
Child child1 = new Child { ChildId = 1, Name="John Jr." };
Child child2 = new Child { ChildId = 2, Name="Betty" };
newParent.Childs.Add(child1);
newParent.Childs.Add(child2);
Session["parent"] = newParent;
}
}
}
Web.Config (sensitive data removed):
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere"/>
<section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere"/>
</configSections>
<connectionStrings>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime/>
<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
<providers>
<add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
</providers>
</sessionState>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<dataCacheClients>
<dataCacheClient name="default">
<autoDiscover isEnabled="true" identifier="[cachename].cache.windows.net"/>
<securityProperties mode="Message" sslEnabled="false">
<messageSecurity authorizationInfo="[CacheKey]"/>
</securityProperties>
</dataCacheClient>
</dataCacheClients>
</configuration>
After more research I was unable to find a way to store Linq to Sql objects in session while using Windows Azure Caching Service. I ran into the same issue with other out of process session mechanisms like SQL Server based session state. The best solution for me was to use a SessionHelper object similar to the one in this article. I changed the line in Page Load where the object is stored into the Session to:
SessionHelper.Set("Parent", newParent);
In the end, my problem was not specifically related to Windows Azure caching, but very similar to this article on stackoverflow
I realized this question has been previously asked but with little in the way of example code, so I am asking again but with at least a little bit of direction.
After hours of searching, I have come up with the following partial implementation.
namespace GoogleAnalyticsAPITest.Console
{
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
string Scope = Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
string scopeUrl = "https://www.googleapis.com/auth/" + Scope;
const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
const string ServiceAccountUser = "nnnnnnnnnnn#developer.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(#"7039572692013fc5deada350904f55bad2588a2a-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = scopeUrl,
ServiceAccountId = ServiceAccountId//,ServiceAccountUser = ServiceAccountUser
};
IAuthorizationState state = AssertionFlowClient.GetState(client);
AnalyticsService service = new AnalyticsService(authenticator);
string profileId = "ga:xxxxxxxx";
string startDate = "2010-10-01";
string endDate = "2010-10-18";
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
GaData data = request.Fetch();
}
}
}
I have a couple issues. The call to AssertionFlowClient.GetState(client) results in a "invalid_scope" response as seen in the DotNetOpenAuth log of
2012-10-19 13:27:36,272 (GMT-4) [8] INFO DotNetOpenAuth - DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official)
2012-10-19 13:27:36,284 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - Preparing to send AssertionFlowMessage (2.0) message.
2012-10-19 13:27:36,294 (GMT-4) [8] INFO DotNetOpenAuth.Messaging.Channel - Prepared outgoing AssertionFlowMessage (2.0) message for https://accounts.google.com/o/oauth2/token:
grant_type: assertion
assertion_type: http://oauth.net/grant_type/jwt/1.0/bearer
assertion: (a bunch of encoded characters go here)
2012-10-19 13:27:36,296 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - Sending AssertionFlowMessage request.
2012-10-19 13:27:36,830 (GMT-4) [8] DEBUG DotNetOpenAuth.Http - HTTP POST https://accounts.google.com/o/oauth2/token
2012-10-19 13:27:36,954 (GMT-4) [8] ERROR DotNetOpenAuth.Http - WebException from https://accounts.google.com/o/oauth2/token:
{
"error" : "invalid_scope"
}
I have tried specifying one or both of ServiceAccountId and ServiceAccountUser with no luck.
Second, even if I get an IAuthorizationState, I am not sure how I get an IAuthenticator that can be passed to the AnalyticsService constructor.
The following is the web.config I use to enable DotNetOpenAuth logging.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, publicKeyToken=1b44e1d426115821" />
<!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/>-->
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth">
<section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
<section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
</sectionGroup>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="DotNetOpenAuth.log"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="100KB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<appender name="TracePageAppender" type="OpenIdProviderWebForms.Code.TracePageAppender, OpenIdProviderWebForms">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="TracePageAppender"/>
</root>
<!-- Specify the level for some specific categories -->
<logger name="DotNetOpenAuth">
<level value="ALL"/>
</logger>
</log4net>
<dotNetOpenAuth>
<!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
<!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
<!--<messaging clockSkew="00:10:00" lifetime="00:03:00" strict="true">-->
<!--<messaging>
<untrustedWebRequest timeout="00:00:30" readWriteTimeout="00:00:01.500" maximumBytesToRead="1048576" maximumRedirections="10">
<whitelistHosts>
-->
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--
<add name="localhost"/>
</whitelistHosts>
</untrustedWebRequest>
</messaging>-->
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="false"/>
</dotNetOpenAuth>
<appSettings>
<!--<add key="log4net.Internal.Debug" value="true" />-->
</appSettings>
<runtime>
</runtime>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
The following code, corrected from my original question, is based on the example provided by Ian Fraser at:
https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ
His code addressed three issues:
It appears as though AnalyticsService.Scopes.AnalyticsReadonly does not work, at least not for me or the way I am doing it.
For some reason, the ServiceAccountUser must be assigned to the ServiceAccountId property of the AssertionFlowClient instance.
OAuth2Authenticator provides the IAuthenticator that I was looking for.
In your project, include references to:
Lib\DotNetOpenAuth.dll
Lib\Google.Apis.dll
Lib\Google.Apis.Authentication.OAuth2.dll
Services\AnalyticsService\Google.Apis.Analytics.v3.dll
-
namespace GoogleAnalyticsAPITest.Console
{
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
const string ServiceAccountUser = "nnnnnnnnnnn#developer.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(#"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
//,ServiceAccountUser = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
AnalyticsService service = new AnalyticsService(authenticator);
string profileId = "ga:64968920";
string startDate = "2010-10-01";
string endDate = "2010-10-31";
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
GaData data = request.Fetch();
}
}
}
I was checking out the analytics API yesterday and noticed how undocumented it is and no samples etc.
Any ways, I have created a library that you could use to access analytics easily with couple of lines and make direct databinding to DataTables for data returned it's open source on the github so feel free to contribute :)
https://github.com/rmostafa/DotNetAnalyticsAPI
Usage
Analytics.AnalyticsManager manager = new Analytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"), "YOUR_EMAIL");
manager.LoadAnalyticsProfiles();
List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Visitor.Metrics.visitors);
metrics.Add(Analytics.Data.Session.Metrics.visits);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.city);
System.Data.DataTable table = manager.GetGaDataTable(DateTime.Today.AddDays(-3), DateTime.Today, metrics, dimensions, null, metrics);
There is direct code mapping for All Google API Reporting commands categorized same way like the API so you could it even without reading the API Documentation at all since all features there are documented in the attributes, I have wrote code that parsed the complete api documentation and resourced the Metrics, Dimensions, Calculated Features in an XML that i generated from physical classes that you could use directly like the example above it's fun to play with :) enjoy
https://github.com/rmostafa/DotNetAnalyticsAPI
string scope = Google.Apis.Util.Utilities.GetStringValue(AnalyticsService.Scopes.AnalyticsReadonly);
Here is my working example posted here [1]: Automated use of google-api-dotnet-client with OAuth 2.0 I put a lot the research into finding and piecing the code together hope this saves you some time.
Regarding Richard Collette answer, be careful that using his method if you want to use Analytics API in READONLY mode, the correct way to use it is:
string Scope = "analytics.readonly"
and not
string Scope = AnalyticsService.Scopes.AnalyticsReadOnly.ToString().ToLower()
as he seems to tell that there is a bug. In fact, the bug is that the .toString() method returns analyticsreadonly and NOT analytics.readonly which is the way that Google likes. That's it.
I'm doing some work in Visual Studio 2012 Express Edition. I have added an App.config XML file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
The first thing that happens is a warning comes up that says "The 'configuration' element is not declared". Does anyone know why this is happening? It looks like elements can not be declared inside of until this is resolved.
Thanks!
This is the entire XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Version" value="779" />
<add key="TimeOut" value="60000" />
<add key="LogFileName" value="Log.txt" />
<!-- your Developer Id with eBay -->
<add key="Environment.DevId" value="" />
<!-- your Application Id with eBay -->
<add key="Environment.AppId" value="" />
<!-- your Application Certificate with eBay -->
<add key="Environment.CertId" value="" />
<!-- API Server URL -->
<!-- For production site use: https://api.ebay.com/wsapi -->
<!-- For Sandbox use: https://api.sandbox.ebay.com/wsapi -->
<add key="Environment.ApiServerUrl" value="https://api.sandbox.ebay.com/wsapi" />
<!-- EPS Server URL -->
<!-- For production site use: https://api.ebay.com/ws/api.dll"/-->
<add key="Environment.EpsServerUrl" value="https://api.sandbox.ebay.com/ws/api.dll" />
<!-- eBay Signin URL -->
<!-- For production site use: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn -->
<!-- https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn -->
<add key="Environment.SignInUrl" value="https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn" />
<!-- ViewItem URL -->
<!-- For production site use: http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item={0} -->
<add key="Environment.ViewItemUrl" value="http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item={0}" />
<!-- token is for both API server and EPS server -->
<add key="UserAccount.ApiToken" value="" />
<!-- eBay site ID -->
<add key="UserAccount.eBayUserSiteId" value="0" />
<add key="logexception" value="true"/>
<add key="logmessages" value="true"/>
<add key="logsdkmessages" value="true"/>
<add key="logsdk" value="true"/>
<add key="logfile" value="Log.txt"/>
<!-- Rule Name-->
<add key="RuName" value=""/>
<!-- Set this if you access eBay API server behind a proxy server-->
<add key="Proxy.Host" value =""/>
<add key="Proxy.Port" value =""/>
<!-- set proxy server username/password if necessary-->
<add key="Proxy.Username" value=""/>
<add key="Proxy.Password" value=""/>
Go to XML menu (visual studio top menu item) choose schemas and find for DotNetConfig.xsd and choose Use this schema.
Your problem will resolve for sure
<configuration xmlns="schema URL">
<!-- configuration settings -->
</configuration>
do changes,like above & try
I had the same issue. It is not an error, it is simply a warning; so your application should still compile. I used the following simple config file and the warning is still produced.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime
version="v4.0"sku=".NETFramework,
Version=v4.5"/>
</startup>
</configuration>
It is an issue that has been raised on the MSDN website, but it does not seem to have been satisfactorily resolved. See link below:
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/18a1074f-668f-4fe3-a8d9-4440db797439
I had to
-> Go to XML menu (visual studio top menu item) choose schemas and select DotNetConfig.xsd AND RazorCustomSchema.xsd AND EntityFrameworkConfig_6_1_0.xsd
I just had this warning popup inside an autogenerated xml file while working on a xaml project.
Using Debug->Clean Solution and Debug->Rebuild Solution fixed it. Might want to try that before getting fancy with the schemas.
Visual Studio 2013 Express Edition is missing the DotNetConfig.xsd (https://connect.microsoft.com/VisualStudio/feedback/details/817322/dotnetconfig-xsd-files-not-present-in-vs-2013-express-for-desktop).
So to get rid of the warning in VS 2013 Express:
get a copy of DotNetConfig.xsd from another system or from the web (I used https://gist.github.com/eed3si9n/5dd7dd98ad2b3f668928b23477de35a3)
download to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Xml\Schemas
add the schema following Ramakrishna's answer
The warning should be gone.
Choose use this schema. DotNetConfig.xsd
XLM Menu..... Visual Studio
Works perfectly.
I was having less space on my drive which might have resulted in incomplete loading of my application solution. This "the-configuration-element-is-not-declared" problem got solved after i created some space on my drive.
I also got the same warning. After thinking about for some time I realized my error working with SQL (MS SQL).
Warning: the 'configuration' element is not declared
Using C#
App.Config code:
<connectionStrings>
<add name="dbx" connectionString="Data Source=ServerNameHere;Initial Catalog=DatabaseNameHere;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
*this calls out the database name in the connectionStrings, when I plugged in my SQL code as a practice I always use the database name, schema, then table. This practice didn't carry over well in Visual Studio as I am a beginner. I removed the db name from my SQL syntax and only called from the schema, data table. This resolved the issue for me.
Form.CS:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [DatabaseName].[Schema].[TableName] WHERE [MEPeriod] = '2020-06-01'", con))
Updated to:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Schema].[TableName] WHERE [MEPeriod] = '2020-06-01'", con))
This worked for me, I hope this is found as useful.
I'm in a ASP.NET project where I need to give several parameters to the administrator that is going to install the website, like:
AllowUserToChangePanelLayout
AllowUserToDeleteCompany
etc...
My question is, will be a good thing to add this into the web.config file, using my own configSession or add as a profile varibles? or should I create a XML file for this?
What do you do and what are the cons and favs?
I originally thought about web.config but I then realized that I should mess up with Website configurations and my own web app configuration and that I should create a different file, them I read this post and now I'm on this place... should I do this or that?
I usually use Settings - available via the project properties - Settings. These can be edited and saved in code, and I write a form / web page to edit them.
If you want to use the XML configuration, there's an attribute called file that reads external files.
You could have a web.config file and a someothername.config file. The someothername.config would have settings like:
<appSettings>
<add key="ConnString" value="my conn string" />
<add key="MaxUsers" value="50" />
</appSettings>
And the web.config would have
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="ExternalWeb.config">
<add key="MyKey" value="MyValue" />
</appSettings>
</configuration>
See DevX for the example I stole.
just to let you guys know that I did what configurator recommended but with a twist.
instead of asking all the time (that I need) for
System.Configuration.ConfigurationManager.AppSettings["myKey"];
I just created a static class that would pull this values with what we call by Strongly typed values (so you don't need to remember all the values)
the mySettings class
public static class mySettings
{
public enum SettingsType
{ UserPermitions, WebService, Alerts }
public enum SectionType
{ AllowChangeLayout, AllowUserDelete, MaximumReturnsFromSearch, MaximumOnBatch, SendTo }
public static String GetSettings(SettingsType type, SectionType section)
{
return
ConfigurationManager.AppSettings[
String.Format("{0}_{1}",
Enum.Parse(typeof(SettingsType), type.ToString()).ToString(),
Enum.Parse(typeof(SectionType), section.ToString()).ToString())
];
}
}
the web.config appSettings part
<configuration>
<appSettings file="myApp.config">
<add key="UserPermitions_AllowChangeLayout" value="" />
<add key="UserPermitions_AllowUserDelete" value="" />
<add key="WebService_MaximumReturnsFromSearch" value="" />
<add key="Alerts_SendTo" value="" />
<add key="Alerts_MaximumOnBatch" value="" />
</appSettings>
</configuration>
the entire myApp.config file
<?xml version="1.0" encoding="utf-8" ?>
<!--
###
### This file serves the propose of a quick configuration.
### Administrator can either change this values directly or use the
### Settings tab in the application.
###
-->
<appSettings>
<!-- *** User Access Configuration *** -->
<!-- Allow user to change the panels layout {1: Yes} {0: No} -->
<add key="UserPermitions_AllowChangeLayout" value="1" />
<!-- Allow user to delete a company fro monitoring -->
<add key="UserPermitions_AllowUserDelete" value="1" />
<!-- *** Web Service configuration *** -->
<!-- Maximum responses from the search service -->
<add key="WebService_MaximumReturnsFromSearch" value="10" />
<!-- *** Allerts configuration *** -->
<!-- Send the alerts to the email writeen below -->
<add key="Alerts_SendTo" value="bruno.in.dk#gmail.com" />
<!-- Send an alert when user import more than the number bellow -->
<add key="Alerts_MaximumOnBatch" value="10" />
</appSettings>
So, now I call like this:
p.value = mySettings.GetSettings(
mySettings.SettingsType.WebService,
mySettings.SectionType.MaximumReturnsFromSearch);
Hope that helps someone with the same problem :)
You may also put your configurations in a settings file. In your project, open Properties and go to Settings which looks
like so
To access the values in your code, use Properties.Settings.YourSettingName;
Use Properties.Settings.Default.Reload(); to refresh your settings during runtime