integrate mailchimp api in asp.net - asp.net

I am integrating mailchimp api in asp.net.
web.config:
<add key="APIKey" value="XXXX9dsfij4yZXXXXXXXXXX-XXXX" />
in code
using mailchimp;
IMailChimpManager manager = new MailChimpManager();
when I see what's in 'manager' object, it's null.
how do i get api key from web.config file?

According to:
https://github.com/brandonseydel/MailChimp.Net/blob/master/README.md You have two options here.
First, you can manually read API key from config:
using mailchimp;
using System.Configuration;
//Read API key from config
var apiKey= ConfigurationManager.AppSettings["APIKey"];
IMailChimpManager manager = new MailChimpManager(apiKey);
Second option is that you can change read key to MailChimpApiKey, so change
<add key="APIKey" value="XXXX9dsfij4yZXXXXXXXXXX-XXXX" />
to
<add key="MailChimpApiKey" value="XXXX9dsfij4yZXXXXXXXXXX-XXXX" />
In that case you don't need to pass API key:
using mailchimp;
IMailChimpManager manager = new MailChimpManager();

Related

Can i read environment variable from Azure App Settings by using Environment.GetEnvironmentVariable method?

I am adding Firebase SDK to the server.
The first step is to set the GOOGLE_APPLICATION_CREDENTIALS environment variable,
so I set the environment variable in the Azure Service -> Configuration -> App Setting.
I checked environment variables from kudu too.
And I tried to get an environmental variable from my ASP.NET app using Environment.GetEnvironmentVariable method,
but It returns null and all the other environmental variables of the app settings return null too.
My project is built with .NET Framework 4.8 and MVC5.
Is there any information about this?
using Microsoft.Ajax.Utilities;
using Microsoft.AspNet.Identity;
using Nest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.ServiceModel.Channels;
using System.ServiceModel.Syndication;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace ---.Controllers
{
public class HomeController : Controller
{
public async Task<ActionResult> Index(ActionParams param)
{
...
var appsettings = ConfigurationManager.AppSettings;
var local = appsettings["GOOGLE_APPLICATION_CREDENTIALS"];
var production = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
ViewBag.localEnv = local;
ViewBag.productionEnv = production;
return View("Home", "Index");
}
This project is from my company, so i blocked some information and the language is korean.
I am able to get the Azure Environment variables in my Environment.
Please check the below workaround.
Created a .NET Framework App with MVC.
Installed the below NuGet Packages
Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration
Microsoft.Configuration.ConfigurationBuilders.Environment
System.Configuration.ConfigurationManager
Steps to Install NuGet Package
Right Click on the Solution Explorer => Manage NuGet Packages => Search in the Browse tab
In Web.config file => Under Configuration section add the below settings
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="DefaultEnvironment" mode="Greedy" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>
<appSettings configBuilders="DefaultEnvironment">
<add key="GOOGLE_APPLICATION_CREDENTIALS" value="Set via an environment variable - for example, dev, test, staging, or production connection string." />
</appSettings>
Add the New App setting in Azure Web App Configuration Section.
Initially local web.config file contains the appsettings with some default value. Now I will override the value with Azure App Service Setting.
In HomeController, write the below code.
public ActionResult Index()
{
var appsettings = ConfigurationManager.AppSettings;
var local = appsettings["GOOGLE_APPLICATION_CREDENTIALS"];
var production = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
ViewBag.GOOGLE_APPLICATION_CREDENTIALS = local;
ViewBag.GOOGLE_APPLICATION_CREDENTIALS1 = production;
return View();
}
I am able to get the Environment variable by using both
var appsettings = ConfigurationManager.AppSettings;
appsettings["GOOGLE_APPLICATION_CREDENTIALS"];
and
Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
In Home => Index.cshtml, add the below snippet somewhere in the file
<h2> #ViewBag.GOOGLE_APPLICATION_CREDENTIALS - Local Settings</h2>
<h2> #ViewBag.GOOGLE_APPLICATION_CREDENTIALS1 - Production Settings</h2>
Local App Output
Published App OutPut :
As you can see local settings are overridden by Azure App Settings.
References taken from MSDoc

Ckfinder azure set backend programmatically

I would like to set Azure as backend for CKFinder and I want to read values (account, password) from AppSettings, not CKFinder setting for backend.
smthng like:
<add key="CKFinderBackendAccountName" value="**********" />
<add key="CKFinderBackendAccountKey" value="************" />
So far I have this code and I want only Azure account, password to be read from APPSettings. I see no corresponding property in ConnectorBuilder.
connectorBuilder.LoadConfig()
.SetLicense(licenceDomain, licenceKey)
.SetAuthenticator(customAuthenticator)
.SetRequestConfiguration(
(request, config) =>
{
config.LoadConfig();
var defaultBackend = config.GetBackend("azureBackend");}

Acces-Control-Allow-Origin works with Web.config (IIS7) but not with (WebApiConfig.cs) ASP.NET Cross Origin support

For a project i want to load and view a pdf file with angular-pdfjs. The team uses ASP.net Cross Origin, to Allow-Acces-Control, Headers, Credentials etc.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Replace the default implementation of the ITraceWriter with our custom logger.
config.Services.Replace(typeof (ITraceWriter), new GlobalTraceLogger());
// Replace the default exception logger to be able to log exceptions with NLog
config.Services.Replace(typeof (IExceptionLogger), new GlobalExceptionLogger());
// Replace the default exceptionhandler to be able to handle exceptions globally
config.Services.Replace(typeof (IExceptionHandler), new GlobalExceptionHandler());
// We must enable cors, because otherwise we are not able to commuincate with a java script client
// TODO: We need to restirct the requested resource. Do not allow every origin!
// Do not run this in prodocutive environment
var cors = new EnableCorsAttribute("*", "*", "*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
// Make the default return type JSON
var appXmlType =
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
This works good so far, but if i want to load my pdf file with angular-pdfjs, i get a Cross Origin Error, because Allow-Acces-Control-Origin "*" didn't works for my pdf-url.
(https://img3.picload.org/image/roirrgcw/corsworksnot.png)
But if i using instead of ASP.net Cross Origin Support the Allow-Access-Control of IIS7 in Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested- With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
it works and the pdf will be loaded correctly.
(https://picload.org/image/roirrgci/corsworks.jpg)
But the problem is, at the moment the page is loaded via "file://" and so i get
an error because there is no Access-Control-Allow-Origin for 'null'. That means, my pdf is loading correctly this way, but the login, pictures... won't be loaded anymore. So my question is, if someone knows how i can change the WebApiConfig-Implementation that my pdf-file get an Access-Controll-Allow as well. Or maybe can someone tell where the error could be.
For information:
Thats the way i'm loading the pdf with angular-pdfjs:
<!---------------------------THE PDF VIEWER DIRECTIVE------------------------->
<div pdf-viewer="options" pdf-url="pdfUrl" id="my-viewer" class="col col-lg-10"></div>
<!---------------------------THE PDF VIEWER DIRECTIVE------------------------->
and thats the url, i'm using:
function PdfviewController(ebmGuideLineService, mediaService, $scope, $window) {
var vm = this;
$scope.pdfUrl = 'http://localhost:3787/NCCN_Evidence_Blocks_Melanoma.pdf';
$scope.options = { mouseZoom: false, mousePan: false };
Please tell me, if you need more informations and thank you for your help.

Hangfire.io Dashboard mapped to IIS Virtual Directory

I'm having trouble getting the Hangfire (1.5.8) dashboard to work inside of an IIS Virtual Directoy. Everything works beautifully in my dev environment where my application is simply mapped to the root of localhost. Our beta server, on the other hand, uses Virtual Directories to separate apps and app pools.
It's an ASP.Net MVC site using Hangfire with an OWIN Startup class. It gets deployed to http://beta-server/app-name/. When I attempt to access either http://beta-server/app-name/hangfire or http//beta-server/hangfire I get a 404 from IIS.
For the purposes of troubleshooting this, my IAuthenticationFilter simply returns true.
Here is my Startup.cs, pretty basic:
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
GlobalConfiguration.Configuration
.UseSqlServerStorage(new DetectsEnvironment().GetEnvironment());
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
AuthorizationFilters = new[] {new AuthenticationFilter()}
});
app.UseHangfireServer();
}
}
Does anyone have a working implementation that gets deployed to a Virtual Directory? Are there any OWIN middleware admin/management tools I can use to dig into what URL is getting registered within IIS?
I ended up fixing this simply by adding the HTTPHandler to the section in web.config.
<system.webServer>
<handlers>
<add name="hangfireDashboard" path="hangfire" type="System.Web.DefaultHttpHandler" verb="*" />
</handlers>
</system.webServer>
I had a similar issue in ASP.NET Core 2.0 and it required proper authorization setup (I use a middleware to protect the route, so I did not rely on authorization in my example):
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new [] {new HangfireDashboardAuthorizationFilter()}
});
/// <summary>
/// authorization required when deployed
/// </summary>
public class HangfireDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
///<inheritdoc/>
public bool Authorize(DashboardContext context)
{
// var httpContext = context.GetHttpContext();
// Allow all authenticated users to see the Dashboard (potentially dangerous).
// handled through middleware
return true; // httpContext.User.Identity.IsAuthenticated;
}
}
There is not need to change anything in web.config.
For more information check Hangfire documentation about this topic.
I had the exact same problem. In my case, this was because of bad configuration - the Startup class was not called. So try to add the following to your config file:
<add key="owin:appStartup" value="YourProject.YourNamespace.Startup, YourProject" />
<add key="owin:AutomaticAppStartup" value="true" />
Hope this helps.
Martin

ASP.NET MVC5 Customised Inbound Routing

I'm "playing" around with custom inbound URL routing and have came across a problem.
When I pass my custom route a URL to examine, that ends in *.+, my class is not fired when i submit the request.
An example URL would be "~/old/windows.html"
When I step through this in the debugger, my RouteBase implementation doesn't fire. If i edit the url that i pass to the constructor of my route to try to match against "~/old/windows", my implemetation is fired as expected.
Again, If i change the url ro examine to "~/old/windows." the problem reoccurs.
My Route Implementation is below :-
public class LegacyRoute : RouteBase
{
private string[] _urls;
public LegacyRoute(string[] targetUrls)
{
_urls = targetUrls;
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
string requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath;
if (_urls.Contains(requestedURL, StringComparer.OrdinalIgnoreCase))
{
result = new RouteData(this, new MvcRouteHandler());
result.Values.Add("controller", "Legacy");
result.Values.Add("action","GetLegacyURL");
result.Values.Add("legacyURL", requestedURL);
}
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
In the RoutesConfig file I have registered my route like so :-
routes.MapMvcAttributeRoutes();
routes.Add(new LegacyRoute(new[]{"~/articles/windows.html","~/old/.Net_1.0_Class_Library"}));
Can anyone point out why there is a problem?
By default, the .html extension is not handled by .NET, it is handled by IIS directly. You can override by adding the following section in Web.config under <system.webServer> -
<handlers>
<add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
As pointed out here. The above will route EVERY .html file request to .NET, you might want to be more specific by providing a more complete path if you don't want your routing to handle every .html file.
I've found the problem, and I'm sure this will help out a lot of fellow developers.
The problem is with IIS Express that is running via Visual Studio.
There is a module configured in the applicationhost.config called :-
UrlRoutingModule-4.0
This is how it looks in file :-
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="managedHandler,runtimeVersionv4.0" />
You need to set the preCondition Parameter to "".
To do this :-
Run you app via Visual Studio
Right click on IIS Express in your system tray, select "Show All Applications"
Click on the project you wish to edit, then click the config URL.
Open the file with Visual Studio, Locate the module and ammend.
Hope this helps anyone else, who ran into a similar problem.

Resources