EnableApiKeySupport generates error - swagger

while trying to Add bearer token using Swashbuckle swagger-document
i got this error in SwaggerConfig.cs
swaggeruiconfig does not contain definition for 'EnableApiKeySupport'
do any body know what may be the reason
Update
this is the entire swagger.config
using System.Web.Http;
using WebActivatorEx;
using Swashbuckle.Application;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace AppNameSpace
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.ApiKey("Token")
.Description("Filling bearer token here")
.Name("Authorization")
.In("header");
c.SingleApiVersion("v2", "AppNameSpace");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{
c.EnableApiKeySupport("Authorization", "header");
});
}
protected static string GetXmlCommentsPath()
{
return System.String.Format(#"{0}\bin\AppNameSpace.XML", System.AppDomain.CurrentDomain.BaseDirectory);
}
}
}

This I believe is something on your project outside Swashbuckle, I created a test project with your GlobalConfiguration and it compiles without any error:
https://github.com/heldersepu/csharp-proj/tree/master/WebApi560
On that test project I'm using the following packages:
<package id="Swashbuckle" version="5.6.0" targetFramework="net452" />
<package id="Swashbuckle.Core" version="5.6.0" targetFramework="net452" />
<package id="WebActivatorEx" version="2.0" targetFramework="net452" />
You can try seeing what options are available for the SwaggerUiConfig...
in your VisualStudio project remove the EnableApiKeySupport and let the IntelliSense show you what's available, you should see something like:
If yours does not look like the one on my picture. You might be overwriting the class SwaggerUiConfig.

Related

Episerver Output Cache - implementing

I am trying to follow some instructions I found online in order to implement output caching for episerver.
In my web.config I have set up the following:
<caching>
<outputCache enableOutputCache="true">
</outputCache>
<outputCacheSettings>
<outputCacheProfiles>
<add name="ClientResourceCache" enabled="true" duration="3600" varyByParam="*" varyByContentEncoding="gzip;deflate" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
As a test, I selected StartPageController.cs and added the [ContentOutputCache] tag like so:
[ContentOutputCache]
public class StartPageController : PageControllerBase<StartPage>
{
public ActionResult Index(StartPage currentPage)
{
var model = PageViewModel.Create(currentPage);
if (SiteDefinition.Current.StartPage.CompareToIgnoreWorkID(currentPage.ContentLink))
{
var editHints = ViewData.GetEditHints<PageViewModel<StartPage>, StartPage>();
editHints.AddConnection(m => m.Layout.Logotype, p => p.SiteLogotype);
editHints.AddConnection(m => m.Layout.Footer, p => p.FooterBlock);
}
return View(model);
}
}
}
Then the instructions say:
At some point on a page load you need to add the following code:
public void SetResposneHeaders()
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(2.0));
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
HttpContext.Current.Response.Cache.SetValidUntilExpires(true);
}
Due to my limited knowledge of .NET, MVC etc.. this part confuses me as I am not sure in which file to place it and where? Does this go in StartPageController.cs? Or somewhere else?
Any pointers would be appreciated.
The instructions I am trying to follow are here.

Error The path in 'value' must start with '/' in ASP.NET Core 2 in application deploy

I'm trying to deploy an asp net core 2 application, all seems to be ok, I'm using deploy Files option in VS2017, to my path inetpub\wwwroot\App1 folder, I add the application.
I browse to the path http://localhost:8088/App1/Home/Index/
then I see :
ArgumentException: The path in 'value' must start with '/'.
Nombre del parámetro: value
Microsoft.AspNetCore.Http.PathString..ctor(string value)
Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler(IApplicationBuilder
app, string errorHandlingPath)
OCIndicadoresOperativoClientes.Startup.Configure(IApplicationBuilder
app, IHostingEnvironment env) in Startup.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder
app)
Microsoft.AspNetCore.Server.IISIntegration.IISSetupFilter+<>c__DisplayClass3_0.b__0(IApplicationBuilder
app)
Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter+<>c__DisplayClass0_0.b__0(IApplicationBuilder
builder)
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
below you can see the code of Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace App1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(25);
options.Cookie.HttpOnly = true;
});
services.AddAuthenticationCore();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseExceptionHandler("App1/Home/Error");
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Home",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "Shippers",
template: "{controller=ControllerB}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
routes.MapSpaFallbackRoute(
name: "ControllerB",
defaults: new { controller = "ControllerB", action = "Index" });
});
}
}
}
also, I will include the webconfig details:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\App1.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>
Do you see any error? i would appreciate your help!
Based from stack trace, the error occurred in this line:
app.UseExceptionHandler("App1/Home/Error");
Currently you're using this overload of UseExceptionHandler which expects URL path:
public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseExceptionHandler (
this Microsoft.AspNetCore.Builder.IApplicationBuilder app,
string errorHandlingPath);
Note that errorHandlingPath parameter requires proper URL format because it will be used to call PathString constructor, hence you should add slash on the beginning of URL:
app.UseExceptionHandler("/App1/Home/Error");
Similar issue: Startup.cs - The path in 'value' must start with '/'
I also had this issue. It was coming because the exception handling path is expected to start with a "/"
The error was:
ArgumentException: The path in 'value' must start with '/'. Nombre del parámetro: value Microsoft.AspNetCore.Http.PathString..ctor(string value) Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler(IApplicationBuilder app, string errorHandlingPath)
Fixed by replacing
app.UseExceptionHandler("Home/Error");
with
app.UseExceptionHandler("/Home/Error");
Also you can try deploying with
app.UseDeveloperExceptionPage();
and find the error if any.

How to configure HTML Minification in ASP.NET MVC

I would like to configure HTML minification to my ASP>NET MVC5 web application.
I installed Nuget
Install-Package WebMarkupMin.Mvc
Then I add Filter Attributte:
[MinifyHtmlAttribute]
public ActionResult Index()
{
return View();
}
But the HTML minification does not work.
Nuget Installation add few lines to the web.config:
<sectionGroup name="webMarkupMin">
<section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" />
<section name="webExtensions" type="WebMarkupMin.Web.Configuration.WebExtensionsConfiguration, WebMarkupMin.Web" />
</sectionGroup>
<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
<core>
<css>
<minifiers>
<add name="NullCssMinifier" displayName="Null CSS Minifier" type="WebMarkupMin.Core.Minifiers.NullCssMinifier, WebMarkupMin.Core" />
<add name="KristensenCssMinifier" displayName="Mads Kristensen's CSS minifier" type="WebMarkupMin.Core.Minifiers.KristensenCssMinifier, WebMarkupMin.Core" />
</minifiers>
</css>
<js>
<minifiers>
<add name="NullJsMinifier" displayName="Null JS Minifier" type="WebMarkupMin.Core.Minifiers.NullJsMinifier, WebMarkupMin.Core" />
<add name="CrockfordJsMinifier" displayName="Douglas Crockford's JS Minifier" type="WebMarkupMin.Core.Minifiers.CrockfordJsMinifier, WebMarkupMin.Core" />
</minifiers>
</js>
<html whitespaceMinificationMode="Medium" removeHtmlComments="true"
removeHtmlCommentsFromScriptsAndStyles="true"
removeCdataSectionsFromScriptsAndStyles="true"
useShortDoctype="true" useMetaCharsetTag="true"
emptyTagRenderMode="NoSlash" removeOptionalEndTags="true"
removeTagsWithoutContent="false" collapseBooleanAttributes="true"
removeEmptyAttributes="true" attributeQuotesRemovalMode="Html5"
removeRedundantAttributes="true"
removeJsTypeAttributes="true" removeCssTypeAttributes="true"
removeHttpProtocolFromAttributes="false"
removeHttpsProtocolFromAttributes="false"
removeJsProtocolFromAttributes="true"
minifyEmbeddedCssCode="true" minifyInlineCssCode="true"
minifyEmbeddedJsCode="true" minifyInlineJsCode="true"
processableScriptTypeList="" minifyKnockoutBindingExpressions="false"
minifyAngularBindingExpressions="false" customAngularDirectiveList="" />
<logging>
<loggers>
<add name="NullLogger" displayName="Null Logger" type="WebMarkupMin.Core.Loggers.NullLogger, WebMarkupMin.Core" />
<add name="ThrowExceptionLogger" displayName="Throw exception logger" type="WebMarkupMin.Core.Loggers.ThrowExceptionLogger, WebMarkupMin.Core" />
</loggers>
</logging>
</core>
</webMarkupMin>
The html element was added by me manually according to documentation.
Am I missing something?
Web application may be in debug mode. In order to switch it to release mode you need to edit the Web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
<system.web>
<compilation debug="false" ... />
...
</system.web>
...
</configuration>
In addition, you can disable dependence on web application mode. Using the following settings:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
<webExtensions disableMinificationInDebugMode="false"
disableCompressionInDebugMode="false" />
...
</webMarkupMin>
...
</configuration>
So large library with so difficult usage and configuration... Are you sure need all this for just the HTML minification?
Create a new filter under the Filters subfolder of your project and call it CompactHtmlFilterAttribute Use the following code:
public class CompactHtmlFilterAttribute : ActionFilterAttribute
{
public class WhitespaceFilter : MemoryStream
{
private string Source = string.Empty;
private Stream Filter = null;
public WhitespaceFilter(HttpResponseBase HttpResponseBase)
{
Filter = HttpResponseBase.Filter;
}
public override void Write(byte[] buffer, int offset, int count)
{
Source = UTF8Encoding.UTF8.GetString(buffer).Replace("\r", "").Replace("\n", "").Replace("\t", "");
Filter.Write(UTF8Encoding.UTF8.GetBytes(Source), offset, UTF8Encoding.UTF8.GetByteCount(Source));
}
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
#if DEBUG
base.OnActionExecuting(filterContext);
#else
try
{
filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response);
}
catch (Exception) { }
#endif
}
}
Pay atention on the #if DEBUG dirrective. HTML will be minified only in release configuration, while on debug the original code will be kept for the better readability.
Add this attribute to the controller methods
[CompactHtmlFilter]
public ActionResult Index()
{
return View();
}
and we're done.
You need to add the following to enable the webextensions (from the doc):
<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
…
<webExtensions enableMinification="true" disableMinificationInDebugMode="true"
enableCompression="true" disableCompressionInDebugMode="true"
maxResponseSize="100000" disableCopyrightHttpHeaders="false" />
…
</webMarkupMin>
Note that it's outside the <core> element.
also in your view markup you should have the attribute as:
[MinifyHtml]
Itshouldn't have the ..Attribute at the end of it.

NHibernate.Search with S#arp Architecture

Has anyone managed to get nhibernate.search (Lucene) to work with S#arp Architecture? I think I have it all wired up correctly except Luke shows no records or indexes when I run my indexing method. The index files for the entity are created (segments.gen & segments_1) but both are 1kb in size which explains why Luke shows no data.
I execute no other code specific to getting search to work, am I missing some initialisation calls? I assume the listeners get picked up automatically by nhibernate.
In my Web project I have:
NHibernate.config
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.connection_string">Data Source=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=True;</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="show_sql">true</property>
<property name="generate_statistics">true</property>
<property name="connection.release_mode">auto</property>
<property name="adonet.batch_size">500</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-insert'/>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-update'/>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-delete'/>
</session-factory>
</hibernate-configuration>
Web.Config
<configSections>
...
<section name="nhs-configuration" type="NHibernate.Search.Cfg.ConfigurationSectionHandler, NHibernate.Search" requirePermission="false" />
</configSections>
<nhs-configuration xmlns='urn:nhs-configuration-1.0'>
<search-factory>
<property name="hibernate.search.default.directory_provider">NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
<property name="hibernate.search.default.indexBase">~\Lucene</property>
</search-factory>
</nhs-configuration>
My entity is decorated as follows:
[Indexed(Index = "Posting")]
public class Posting : Entity
{
[DocumentId]
public new virtual int Id
{
get { return base.Id; }
protected set { base.Id = value; }
}
[Field(Index.Tokenized, Store = Store.Yes)]
[Analyzer(typeof(StandardAnalyzer))]
public virtual string Title { get; set; }
[Field(Index.Tokenized, Store = Store.Yes)]
[Analyzer(typeof(StandardAnalyzer))]
public virtual string Description { get; set; }
public virtual DateTime CreatedDate { get; set; }
...
}
And I run the following to create the index
public void BuildSearchIndex()
{
FSDirectory directory = null;
IndexWriter writer = null;
var type = typeof(Posting);
var info = new DirectoryInfo(GetIndexDirectory());
if (info.Exists)
{
info.Delete(true);
}
try
{
directory = FSDirectory.GetDirectory(Path.Combine(info.FullName, type.Name), true);
writer = new IndexWriter(directory, new StandardAnalyzer(), true);
}
finally
{
if (directory != null)
{
directory.Close();
}
if (writer != null)
{
writer.Close();
}
}
var fullTextSession = Search.CreateFullTextSession(this.Session);
// select all Posting objects from NHibernate and add them to the Lucene index
foreach (var instance in Session.CreateCriteria(typeof(Posting)).List<Posting>())
{
fullTextSession.Index(instance);
}
}
private static string GetIndexDirectory()
{
var nhsConfigCollection = CfgHelper.LoadConfiguration();
var property = nhsConfigCollection.DefaultConfiguration.Properties["hibernate.search.default.indexBase"];
var fi = new FileInfo(property);
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fi.Name);
}
Found an answer to my question so here it is in case anyone else comes by this problem.
NHS configuration in web.config contained such lines:
<property name="hibernate.search.default.directory_provider">NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
<property name="hibernate.search.default.indexBase">~\SearchIndex</property>
First line should be removed because in this case NHS consider it as though index shares. It is known NHibernateSearch issue.
If the site is run from IIS, Network Service should have all permissions on search index directory.
Jordan, are you using the latest bits from NHContrib for NHibernate.Search? I just recently updated my bits and I am running into the same situation you are. It works for me on older bits, from about July. But I can't get my indexes to create either. Your config looks right, same as mine. And your indexing method looks good too.
Jordan, there is now an alternative to attribute based Lucene.NET mapping called FluentNHibernate.Search, this project is hosted on codeplex.
http://fnhsearch.codeplex.com/
public class BookSearchMap : DocumentMap<Book>
{
public BookSearchMap()
{
Id(p => p.BookId).Field("BookId").Bridge().Guid();
Name("Book");
Boost(500);
Analyzer<StandardAnalyzer>();
Map(x => x.Title)
.Analyzer<StandardAnalyzer>()
.Boost(500);
Map(x => x.Description)
.Boost(500)
.Name("Description")
.Store().Yes()
.Index().Tokenized();
}
}

Deleting unreferenced child records with nhibernate

I am working on a mvc app using nhibernate as the orm (ncommon framework)
I have parent/child entities: Product, Vendor & ProductVendors and a one to many relationship between them with Product having a ProductVendors collection Product.ProductVendors.
I currently am retrieving a Product object and eager loading the children and sending these down the wire to my asp.net mvc client.
A user will then modify the list of Vendors and post the updated Product back. I am using a custom model binder to generate the modified Product entity. I am able to update the Product fine and insert new ProductVendors.
My problem is that dereferenced ProductVendors are not cascade deleted when specifying Product.ProductVendors.Clear() and calling _productRepository.Save(product).
The problem seems to be with attaching the detached instance. Here are my mapping files:
Product
<?xml version="1.0" encoding="utf-8" ?>
<id name="Id">
<generator class="guid.comb" />
</id>
<version name="LastModified"
unsaved-value="0"
column="LastModified"
/>
<property name="Name" type="String" length="250" />
ProductVendors
<?xml version="1.0" encoding="utf-8" ?>
<id name="Id">
<generator class="guid.comb" />
</id>
<version name="LastModified"
unsaved-value="0"
column="LastModified"
/>
<property name="Price" />
<many-to-one
name="Product"
class="Product"
column="ProductId"
lazy="false"
not-null="true"
/>
<many-to-one
name="Vendor"
class="Vendor"
column="VendorId"
lazy="false"
not-null="true"
/>
Custom Model Binder:
using System;
using Test.Web.Mvc;
using Test.Domain;
namespace Spoked.MVC
{
public class ProductUpdateModelBinder : DefaultModelBinder
{
private readonly ProductSystem ProductSystem;
public ProductUpdateModelBinder(ProductSystem productSystem)
{
ProductSystem = productSystem;
}
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var product = bindingContext.Model as Product;
if (product != null)
{
product.Category = ProductSystem.GetCategory(new Guid(bindingContext.ValueProvider["Category"].AttemptedValue));
product.Brand = ProductSystem.GetBrand(new Guid(bindingContext.ValueProvider["Brand"].AttemptedValue));
product.ProductVendors.Clear();
if (bindingContext.ValueProvider["ProductVendors"] != null)
{
string[] productVendorIds = bindingContext.ValueProvider["ProductVendors"].AttemptedValue.Split(',');
foreach (string id in productVendorIds)
{
product.AddProductVendor(ProductSystem.GetVendor(new Guid(id)), 90m);
}
}
}
}
}
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update(Product product)
{
using (var scope = new UnitOfWorkScope())
{
//product.ProductVendors.Clear();
_productRepository.Save(product);
scope.Commit();
}
using (new UnitOfWorkScope())
{
IList<Vendor> availableVendors = _productSystem.GetAvailableVendors(product);
productDetailEditViewModel = new ProductDetailEditViewModel(product,
_categoryRepository.Select(x => x).ToList(),
_brandRepository.Select(x => x).ToList(),
availableVendors);
}
return RedirectToAction("Edit", "Products", new {id = product.Id.ToString()});
}
The following test does pass though:
[Test]
[NUnit.Framework.Category("ProductTests")]
public void Can_Delete_Product_Vendors_By_Dereferencing()
{
Product product;
using(UnitOfWorkScope scope = new UnitOfWorkScope())
{
Console.Out.WriteLine("Selecting...");
product = _productRepository.First();
Console.Out.WriteLine("Adding Product Vendor...");
product.AddProductVendor(_vendorRepository.First(), 0m);
scope.Commit();
}
Console.Out.WriteLine("About to delete Product Vendors...");
using (UnitOfWorkScope scope = new UnitOfWorkScope())
{
Console.Out.WriteLine("Clearing Product Vendor...");
_productRepository.Save(product); // seems to be needed to attach entity to the persistance manager
product.ProductVendors.Clear();
scope.Commit();
}
}
Going nuts here as I almost have a very nice solution between mvc, custom model binders and nhibernate. Just not seeing my deletes cascaded. Any help greatly appreciated.
Chev
If you want your child entities were deleted when parent is deleted you need to set
cascade="all-delete-orphan"
option in collection mapping. More about cascading options you can find here
Needed to call the Merge method of the session: ISession.Merge(product)

Resources