Unit Testing for Websites or Webforms or .Aspx page: code coverage - asp.net

I have one website which was made in Asp.Net. I want to have the code coverage for the website now.
Can anybody suggest me which are the possible ways to have the code coverage for the website? Suggestions on how to write unit test methods for Webform or .Aspx page are also welcome.

Try following steps to enable code coverage:
- Open the local.testsettings which you can access from Test -> Edit
Test Settings -> Local (local.testsettings)
- List item Select Data and Diagnostics from the list
- Select the Enabled checkbox on the Code Coverage row
- Double-click the Code Coverage row
- Select the assemblies you want to instrument
- Specify a re-signing key file if your assemblies are strong-named
- Click OK
- Click Apply
- Click Close
For unit test you can have seperate class library project in the same solution where you can create unit test method. For example :
/// <summary>
/// Holds test for MapRoles.
/// </summary>
[TestClass]
public class MapRolesTest
{
/// <summary>
/// Perform test on CompareUserRoles.
/// </summary>
[TestMethod]
public void CompareUserRolesTest()
{
//// The class which is inside actual asp.net web application.
MapRoles objMapRoles = new MapRoles();
//// Get role of the user1.
string user1Role = objMapRoles.GetUserRole("Jeet");
//// Get role of the user2.
string user2Role = objMapRoles.GetUserRole("Vishwajeet");
//// Assert.
Assert.AreEqual(user1Role, user2Role);
}
}

Related

Xamarin App - Resource file, how to include an audio file into the AppResources.Designer.cs

I am working on a Xamarin Form App and we use .resx files for the localizations.
I have got a problem where to my Resources folder I would like to add an audio file called Beep.wav.
Previously in the AppResources.Designer.cs I used to have something like this:
/// <summary>
/// Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream Beep
{
get
{
return ResourceManager.GetStream("Beep", resourceCulture);
}
}
but for some reason is not there anymore and when I regenerate that file by adding/removing a string in AppResources.resx file, still it is not there. It does work if I add that manually but everytime we add a new string it gets wiped away.
I am adding some screenshots to give a bit better meaning to what I am trying to achieve:
My resources folder:
My .csproj file for that project
My AppResources.Designer.cs file which should include the piece of code I have typed earlier
How do I get my Beep.wav file included in there?
This is where it is failing as it cannot find "Beep"
private static readonly ISimpleAudioPlayer _beepPlayer;
static MediaPlayerHelper()
{
_beepPlayer = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
_beepPlayer.Load(Resources.AppResources.Beep); <--Error
}
Thanks
After creating the .resx file, change Strings to Audio.
Click Add Resource to add the .wav file.
After that, it would generate the code below in AppResources.Designer.cs.
/// <summary>
/// Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream WAV_1MG {
get {
return ResourceManager.GetStream("WAV_1MG", resourceCulture);
}
}

Customizing auto generated Swagger definitions

I have swagger setup so that it generates the open Api Specification & Swagger Ui on project startup using NSwag based on the controllers in my WebApi.
I would like to enhance the swagger Ui to include
A summary/description for each endpoint
Example parameter inputs for endpoints that require them
Example request body for POST calls
An example access token that can be used only in the swagger documentation to easily authenticate and be able to try everything out (a bit like in this example https://petstore.swagger.io/)
I'm new to NSwag and unsure how to approach adding these enhancements to my code, like where to add them, what i need to use (annotations on controllers? XML comments? another way?) I've tried editing the specification in 'Swagger Editor' but don't see how this can be the way to go since this gets re-generated on every application startup.
I've read the NSwag documentation but that seems to be all about adding the ASP.NET Core middleware, which I already have configured.
Edit:
I now have a description at the top of the page, and have been able to add an example with the remarks tag in XML comments - is there a more elegant way to do this rather than using XML comments?
A description at the top of the page
To customize the API info and description using Nswag, in the Startup.ConfigureServices method, a configuration action passed to the AddSwaggerDocument method adds information such as the author, license, and description:
services.AddSwaggerDocument(config =>
{
config.PostProcess = document =>
{
document.Info.Version = "v1";
document.Info.Title = "ToDo API";
document.Info.Description = "A simple ASP.NET Core web API";
document.Info.TermsOfService = "None";
document.Info.Contact = new NSwag.OpenApiContact
{
Name = "Shayne Boyer",
Email = string.Empty,
Url = "https://twitter.com/spboyer"
};
document.Info.License = new NSwag.OpenApiLicense
{
Name = "Use under LICX",
Url = "https://example.com/license"
};
};
});
The Swagger UI displays the version's information as below:
A summary/description for each endpoint Example parameter inputs for
endpoints that require them Example request body for POST calls An
example access token that can be used only in the swagger
documentation to easily authenticate and be able to try everything out
(a bit like in this example https://petstore.swagger.io/)
You could add the description/example by adding the following elements to the action header.
Use the <summary> element to describe the Endpoint.
Use the <remarks> element to supplements information specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element content can consist of text, JSON, or XML. You could also use it to add sample.
Use the <param> element to add the required parameters. Besides, you could also use the Data annotations attribute with the Model, it will change the UI behavior.
Use the <response> elements to describe response types.
sample code as below:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="todoitem"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
#region snippet_CreateActionAttributes
[ProducesResponseType(StatusCodes.Status201Created)] // Created
[ProducesResponseType(StatusCodes.Status400BadRequest)] // BadRequest
#endregion snippet_CreateActionAttributes
#region snippet_CreateAction
[HttpPost]
public ActionResult<TodoItem> Create(TodoItem todoitem)
{
_context.TodoItems.Add(todoitem);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = todoitem.Id }, todoitem);
}
The Swagger UI now looks as below:
More detail information, please check the following tutorials:
Customize API documentation using NSwag
Customize API info and description using Swashbuckle
Figured this out now, ended up using operation processors to configure the Swagger UI/OpenApi endpoint summary, request examples, path parameter example values and the possible UI response codes
There isn't a lot of documentation online for doing it this way (all i could find was the XML comment way of doing it so this took a lot of trial and error to get this working)
Posting my solution here for anyone else who would prefer not to clutter up their controllers with XML comments.
Apply OpenApiOperationProcessor attribute to the controller action
Create the Operation Processor and code the SwaggerUI customizations
Example values for path parameters can be filled out as so

Error : Value cannot be null. Parameter name : path 1, when add a new Azure Mobile Apps table Controller

It's the first time I create a back end for my Xamarin.Forms application. I follow instructions on Azure Portal -> Quick-Start, create a data connection, choose c# in step 2 and download the project.
Build it and now I want to add a new table. So :
I add the class in DataObjects folder.
I add the line in the Context file : public DbSet<Coffee> Coffees{ get; set; }
And when I try to add the Azure Mobile Apps table controller, an error message tell me :
Value cannot be null. Parameter name : path1.
What can I do to fix that ?
Sorry for my bad English.
Have a nice day!
I have the same problem, and the problem is also mentioned on the Visual Studio Development community: https://developercommunity.visualstudio.com/content/problem/563354/adding-a-new-azure-mobile-apps-table-controller-or.html
Meanwhile you can work around the problem by creating the controller in code. I've tested the following steps for a Azure Mobile Apps Table Controller for a Xamarin Forms app:
Add a new class to the Controllers folder, i.e. {YourDataObject}Controller.cs
Take an existing and working controller and copy the code into the new controller file.
Replace {OldMobileAppName}Service and {OldMobileAppName}Context with {NewMobileAppName}Service and {NewMobileAppName}Context
Replace {OldDataObjectName} with {NewDataObjectName}
Finally publish your solution.
Configuring a Table Controller requires three steps:
Create a Data Transfer Object (DTO) class.
Configure a table reference in the Mobile DbContext class.
Create a table controller.
A Data Transfer Object (DTO) is a plain C# object that inherits from EntityData. An example from the documentation:
public class TodoItem : EntityData
{
public string Text { get; set; }
public bool Complete {get; set;}
}
Please reference this documentation for more information.

Swashbuckle <summary> alternative

Lets say I have the following Method:
/// <summary>
/// Just a Method
/// </summary>
[HttpGet()]
[Produces("plain/text")]
public IActionResult Foo() => this.Ok("Some Data..");
Swagger is showing me the following:
Can I achieve the same result, without using <summary> ? Is there an attribute or something I could use?
Iam asking because if I run my project on my machine everything works fine, but if i run it on another it doesnt show the description "Just a Method".
It seems like the XML comments get ignored..
I can't post a single peace of the code so please just tell me if theres a work around so i dont have to use <summary>.
Thanks!

What does DotLess' "web" attribute do exactly?

The dotless documentation is quite limited. I can't find much information at all about the configsection options - especially what the "web" attribute does.
Can anyone enlighten me?
The code is normally pretty good documentation for open source projects ;)
Grab a copy of the code and look in dotless.Core > configuration > DotlessConfiguration.cs you will see some handy comments about all the config elements - this is the Web one
/// <summary>
/// Whether this is used in a web context or not
/// </summary>
public bool Web { get; set; }
Admittedly it doesn't tell you a great deal but find the references to that property and you come across only one place in the code where it is used -
if (!configuration.Web)
RegisterLocalServices(pandora);
Which starts to give you a better clue as to what it does which is this
protected virtual void RegisterLocalServices(FluentRegistration pandora)
{
pandora.Service<ICache>().Implementor<InMemoryCache>();
pandora.Service<IParameterSource>().Implementor<ConsoleArgumentParameterSource>();
pandora.Service<ILogger>().Implementor<ConsoleLogger>().Parameters("level").Set("error-level");
pandora.Service<IPathResolver>().Implementor<RelativePathResolver>();
}
So it sets up in memory caching, logging to the console etc (i.e services it uses if not in a web context)

Resources