ASP.NET Web API Help Page documentation using Xml comments on controllers - asp.net-web-api

I installed the ASP.NET Web API Help Page package and would like to use it to generate documentation for my API controller actions using the Xml comments already on them.
I came across an article on Yao's MSDN blog where he discusses how the documentation can be generated based on the XML comments.
However, in the Register method of HelpPageConfig, the SetDocumentationProvider method expects an instance of XmlDocumentationProvider constructed with a physical path to an Xml documentation file.
Is there another way to do this? I'm not clear why I need to point to an Xml documentation file.
Thanks

If you still problem then see below steps.
Step 1 - Add comment on the controller level
// GET api/documentation
/// <summary>
/// This is how we create a documentation
/// </summary>
/// <returns></returns>
public IEnumerable<string> Get()
Step 2 - Build Property
Project Properties page and set up the xml output for documentation
Step 3 - HelpPage Config
To set up the HelpPageConfig to use our documentation xml file, go to ~\Areas\HelpPage\HelpPageConfig.cs.
By default, the config.SetDocumentationProvider statement is commented out. Use that statement, and point the location of DocumentationProvider to our xml file:
public static void Register(HttpConfiguration config)
{
// Uncomment the following to use the documentation from XML documentation file.
config.SetDocumentationProvider(
new XmlDocumentationProvider(
HttpContext.Current.Server.MapPath("~/App_Data/Documentation.xml")));
}
EDIT:
The location of the HelpPageConfig in a new Web API 2.2 project created in VS2013 is ~\Areas\HelpPage\App_Start\HelpPageConfig.cs

The XmlDocumentationProvider is looking for the xml file(having your xml code comments) which gets generated when you compile your project.
You can enable generating this by going to your project Properties -> Build -> Output. Here select the checkbox for XML Documentation file.

I know that this question is answered, but in case it helps someone
I have found this page because of looking for solution for documentation for IHttpActionResult
How to add IHttpActionResult into documentation

Related

How do I reference the CORS namespace in WebApiConfig.cs?

I want to add CORS support to a locally hosted web api 2 project following this tutorial:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
I have added the CORS package via the package manager:
Install-Package Microsoft.AspNet.Cors
Next, as described in the tutorial, I have added the following line to my webconfig.cs file:
config.EnableCors();
Intellisense is now showing that I need a reference for the EnableCors call. I have searched around the web and the latest documentation I can find states that the following reference is required:
using System.Web.Cors;
However, this reference does not resolve the EnableCors call. Can anyone explain what reference namespace is needed?
Thank you for your help!
UPDATE! I got this problem figured out! In Nuget, I loaded Microsoft.AspNet.WebApi.Cors. The reference in the WebConfig.cs file becomes
using System.Web.Http.Cors;
At the beginning of the webConfig.cs file, add the following lines, changing the URL for your specific situation:
var cors = new EnableCorsAttribute("http://localhost:57357", "*", "*");
config.EnableCors(cors);
In the tutorial, an attribute is used. If you wish to use an attribute, then add the call to enable CORS in the WebConfig.cs file, shown here:
config.EnableCors();
I hope this answer provides some guidance to others dealing with this problem. Happy coding!

How can I replace config file database links in one place in source code? (asp.net/razor)

I have an ASP.NET/Razor 3 web application which uses a SQL Server database via MS EntityFramework.
If/when I want to change the database connection string, for example to change the password or point to a different database (e.g. test vs. live), the string needs to replaced in about seven places in three different XML config files in the project (app.config, web.config, and app.release.config), which is an error-prone pain.
Worse, the default web server behavior on unhandled exceptions can include displaying sections of the config files to web users, which has in fact resulted in the web server displaying the lines that show the database path and password over the web. Not good.
For both reasons, and because this is not a product for which anyone would ever just edit the config file on the server (any change is pretty much, and may as well be, a build operation), I would much prefer to have the database connection information compiled into the web application and loaded from code rather than a config file, and to be able to do this such that when I want to change the database information, I can do it in one place instead of seven.
How would I achieve this?
The database connection string(s) can be set up centrally in 1 place, in the Global.asax.cs file, as part of the Application State, and then referenced from anywhere else in the project.
Step-1: Define the connection string(s) as static variables in Global.asax.cs:
namespace TestProject
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static string ConnectionString1;
public static string ConnectionString2;
protected void Application_Start()
{
#region Build application state for the app-specific items needed by us
ConnectionString1 = "Server=yourserver;Database=yourdb;etc etc";
ConnectionString2 = "Server=yourserver;Database=yourdb;etc etc";
#endregion
#region Code auto-generated and needed by system - do not change
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
#endregion
}
}
}
Step-2: Use the strings from anywhere else in the project:
string cnxStr1 = TestProject.MvcApplication.ConnectionString1;
string cnxStr2 = TestProject.MvcApplication.ConnectionString2;
(Please note that by default, the strings would be accessible only from within the same project. You will need to add references to the project if you need to use the strings from any other project within the same solution.)
The answer above by Krishna is pretty good. For me I would personally prefer to have them as static string in a static class and use it where ever is needed.
If you don't want to put the connection strings in the global file, you can:
Create a separate .config file for connection strings. e.g.
connectionStrings.config.
Create a hard-link to this file or the
folder containing this file that's in the same directory as your
other application.config and web.config files.
Set the configSource property on the connectionStrings element in each app.config or
web.config.
From then on, you only have one place to manage your connection strings that are common between apps.
The reason for the hard link is that configSource must reference a file in the same folder or sub-folder of the folder containing the application config.
Note that changing the connection strings will recycle all your web application pools that use them. For console, desktop, and service apps, you will have to restart for changes to take effect.
For the second problem you describe, you could have a separate connectionStrings.config file for each environment: development, test, production. Using config transforms or some other process, you only have to update the configSource property in each connectionString element to switch environments.

Server Error with the griffin.mvccontrib package in asp.net

In order to be able to translate my data annotations in my model with a resource file, I saw that many people recommend the solution offered by jgauffin.
However, when I follow the localization tutorial my project cannot launch.
The problematic code is this one, which is supposed to go in the Global.asax.cs file:
ModelValidatorProviders.Providers.Add(
new LocalizedModelValidatorProvider(stringProvider)
);
It says that the LocalizedModelValidatorProvider constructor does not take any arguments, which is also shown by other tutorials.
But when I change the line like this:
ModelValidatorProviders.Providers.Add(
new LocalizedModelValidatorProvider()
);
I get the following error in the browser:
Attempted to access an element as a type incompatible with the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.
The griffin.mvccontrib packages were installed with NuGet under Visual Studio 2012. Any idea what I am doing wrong ?
You might find this link helpful
Here is how I did the registration in the above link:
ResourceStringProvider myResouceFile = new ResourceStringProvider(ModelsResources.ResourceManager);
//ModelsResources is my resource file generated class
GriffinStringsProvider griffinStringsProvider = new GriffinStringsProvider(myResouceFile);
ValidationMessageProviders.Clear();
ValidationMessageProviders.Add(griffinStringsProvider);
ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(myResouceFile);
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
Make sure you are including the right assemblies
using System.Resources;
using Griffin.MvcContrib.Localization;
using Griffin.MvcContrib.Localization.ValidationMessages;
Also the assembly for your Resource file.

Generating version specific help documentation pages for ASP.NET Web API application

I am using the WebAPI Versioning package to version my API by the X-Api-Header by using the "VersionHeaderVersionedControllerSelector". I am also using the Microsoft.AspNet.WebApi.HelpPage to autogenerate documentation for the APIs.
In order for controller versionign to work, they need to be namespaced with the VersionXYZ as the suffix in the namespace so that the "VersionHeaderVersionedControllerSelector" is able to route the request to the appropriate version of the controller like so:
namespace WEBAPI.Api.Controllers.Version1
{ public class ProductsController : ApiController {} }
namespace WEBAPI.Api.Controllers.Version2
{ public class ProductsController : ApiController {} }
This works as intended but when I look at the generated help pages the ApiDescription is including the "VersionXYZ" suffix from the namespace in the ID (GETapi/Version1.Products) and RelativePath(api/Version1.Products) properties.
Ideally what I'd like to do is to have a top level help page which just the API Version numbers and drilling in would show the API the normal way i.e. The ApiDescription.ID = GETapi/Products and the ApiDescription.RelativePath = api/Products
Is there a way to achieve this using the Out of the Box APIs or am I going to need to rollout my own implementation of ApiExplorer
Check out this answer Get Help page works with Api Versioning
Make sure you have configure the versioning right, and you need to get a documentation XML file from your project XXXX.Api.v1 project and place it in the bin folder of the XXXX.Api project.
Unfortunately ApiExplorer does not support duplicate controller names. So by implementing controller versioning this way, your (or the package code) doesn't play nicely with the system.
Consider another alternative where you actually change the controller name (and yes you will have to implement your own solution, but honestly its not that complex). For example make the version be part of the controller name itself (rather than its name space).
e.g. Ver1_ProcuctsController
Now these will start showing up on your help page, and since help page is just content package you can change the logic to make the names that start with verxxx_ to mutate.

Programatically retrieve an attachment stored on a note on a CRM 4.0 entity

How would you suggest working with files that is stored on the note of a entity in Crm. Could you write a generic method that will enable you to access any type of file? Or would it be better to have a method for dealing with each type of file?
For example, we are going to be saving a mix of swf files and xml files on the entity, so would it make sense to have a method each for example:
GetXmlFilesOnAccount(accountid)
GetSwfFilesOnAccount(accountid)
When you upload an attachment to CRM the mimetype is also saved as part of the record information.
The following link contains a nice example of how to download the attachemt using a single method. http://crmscape.blogspot.com/2009/10/ms-crm-40-sending-attachments-to.html
The post is missing the actual query needed to retrieve the annotations but you can tell what columns are required from the method signature.
My suggestion using your methods:
* GetXmlFilesOnAccount(accountid)
* GetSwfFilesOnAccount(accountid)
Retrieve account activitypointers by regardingobjectid(in your case accountid guid)
Loop through returned activitypointers
Get attachments for each activitypointer (activitypointer.activityid = activitymimeattachment.activityid)
Store attachments (disk, etc)
You don't even need two methods. You can retrieve all attachment file types for a given note (annotation) with a single method.
Hope this helps.
I recently started an Open Source Project on CodePlex to accomplish exactly that. Feel free to check out the Project's Web Page at:
http://crmattachdownload.codeplex.com/
You can also view the source code under the "Source Code" tab of that same page.
Pete

Resources