Archive | June 2015

Beginners: Access Modifiers Exemplified

In the recent past, I have been involved in code review where I found a code base which is dominated with “public” access modifiers, and I was like, seriously?. In my recommendations I had to point there was lot to be done in terms of code accessibility levels, not everything belonged to the public :).

And therefore in this post, we will be expounding modifiers found in the .net framework. Modifiers are used to modify the declaration of types(Interface, Class, Struct) and type members (fields, properties,events, delegates, methods).

In C# there are quite a number of modifiers but in this post we are going to major with access modifiers. Access modifiers specifies the accessibility of types and type members. They include

  1. Private
  2. Internal
  3. Protected
  4. Protected internal
  5. Public

Remember only one access modifier that is allowed in a type except when using “protected internal”. Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default access modifier is used

To bring the point closer home, I would like to think of a family set up where we have a father, mother and children, and the father has a few properties including cars.

We will be using the following classes “Calculator.cs” in assembly “CalculatorLib”


public class Calculator
 {
   private void Add()
    {
    }

     internal void Subtract()
     {
     }

     protected void Divide()
     {
     }

     protected internal void Multiply()
     {
     }

     public void Modulus()
     {
     }
 }

The following image shows what of “Calculator.cs” is visible when called from “CalculatorClient.cs” class in the same assembly

Figure 1

Figure 1

The following image shows what of “Calculator.cs” is visible when called from “Program.cs” class in a different assembly

Figure 2

Figure 2

The following image shows what of “Calculator.cs” is visible when called inside one of its own members

Figure 3

Figure 3

The following image shows what of “Calculator.cs” is visible when called from “CalculatorDerived.cs” class which is its derived class

Figure 4

Figure 4

Private

This proves to be the least permissive and restrictive acess modifer.A private member is only visible to the containing type and its members. Its used in class members and nested class. Remember its not used in top level class.

The private method “Add” can only be accessed by any other member within the class and not outside the class. It’s not even visible to other classes within the same assembly.

Refer to “Figure 3”, you be able to identify “Add” method visible in the containing class and not visible to any of the other figures

Internal

This level of accessibility can used in top level classes, nested class and there members. They are acccessed by the members of the same assembly. The use of internal is in scenarios where you intend components in the same assembly to communicate and share functionalities but as without exposing the functionality to the world (other assemblies).

And so even if you give out you component in terms of a .dll, the internal members are not exposed to the consumer of your library/assembly.

Figure 1, 3, and 4, you are able to see “Subtract” since they are in the same assembly. It’s not visible in Figure 2 since that another assembly

Protected.

This is a member modifier, and can also be used with nested classes. Protected members are only visible to derived classes and the declaring type as well. This modifier is used hand in hand in inheritance as we will come to see later. One other note is that struct cannot be protected as they cannot be inherited.

Visible in Figure 3 since its in the declaring class and also in Figure 4 since its “CalculatorClient.cs” has derived from “Calculator”.

Protected internal

Just as the name is suggesting by the combination of the modifiers, it means that every member with this modifier can be assessed by both types in the same assembly as well as derived classes.

“Multiply” is visible in Figure 1 because of the “internal” modifier and visible in Figure 4 because of the “protected” modifier.

Public

This  is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members. Anything with public modifier is visible literally every where.

“Modulus” which is public, is visible anywhere you should be able to see it in every figure above.

Hope this post,helps you to use the access modifiers knowledgeably and confidently.

The source code is hosted on github

Happy coding!!

How To: Convert ASP.NET Web API to Azure API app

In my last post, I introduced and discussed about the new azure API apps.  It’s really nothing more than your asp.net web API with a new way and form to expose the metadata so to speak.  Its actually a web app with other additional features for hosting. Azure API  is hosted within a web app.

In the pipeline to Azure API app, there a gateway which performs other stuff before reaching the Azure API app. The gateway is just another web app able to perform extra functionality like authetication with providers.

Every resource group with that contains an API app also includes a gateway. The azure API app expose there metadate via a new representation swagger. Its a new powerful representation of RESTful API.

In this post we are looking at how to convert an already existing ASP.NET web api to azure api app. I will be using visual studio 2013.

Open visual studio 2013, and create a new ASP.NET Web api.

aspnetwebapi

To keep things simple, I am not using any authentication in this post. We will make a few changes to ValuesController, make sure it look like show below


public class StudentController : ApiController
{
public IHttpActionResult Get()
{
var students = Students();

return Ok(students);
}

private List<Student> Students()
{
var students = new List<Student>();
IGenerationSessionFactory factory = AutoPocoContainer.Configure(
x =>
{
x.Conventions(c => { c.UseDefaultConventions();});
x.AddFromAssemblyContainingType<Student>();
});

//Create a session
IGenerationSession session = factory.CreateSession();
students = session.List<Student>(50)
.First(25)
.Impose(x => x.FirstName, "Bob")
.Next(25)
.Impose(x => x.FirstName, "Alice")
.All()
.Impose(x => x.LastName, "Pius")
.Random(10).Impose(x => x.LastName, "Peter")
.                                                  All().Get().ToList();

return students;
}
}

In our code we are using “autopoco” package to generate object to test with. So far this is just the normal ASP.NET web api. You can run the application and hit “http://localhost:26467/api/Student&#8221; and you will see the response of 50 students.

So how do we convert it to azure API app? Good question, and the essence of this post. To do that you simply add a new package called “swashbuckle” as shown below. Go package manager and search for “swashbuckle”

swashbuckle

When this is installed a new file should be added in your App_Start, “SwaggerConfig.cs”. Ensure your solution looks like below

Swaggerfileconfig

That’s the file that makes your expectations come true. Nothing much, nothing less. So run you application and hit the following url, “http://localhost:26467/swagger&#8221; which takes to a screen like below:

Swagger_documentation

If your screen looks like above then everything so far looks good. So this generates a documentation of all the api operations in the project, you need to know it uses the same pipeline as how ASP.NET WEB api generate help pages.  Click “Try it out!” and you will see a json response from the “GET” operation.

But where is the metadata? Navigate to “http://localhost:26467/swagger/docs/v1&#8221;, and this will generate a metadata file which is json in nature. We will talk on how to use this metadata file to generate a client sdk and other uses.

metadata

So from the image above.

1. Paths holds a collection of the API controllers in the projects

2. Indicate a API controller in our project “/api/Student”

3. Within every API controller, all available operations tagged with the http verb are listed.

4. The responses the operation supports.

That’s it!! 🙂 We have managed to convert/enable an ASP.NET Web api to a azure api app.

Source code can be on github

%d bloggers like this: