Properties – the basics

Properties in C# is a special type of methods called accessors, they are accessed as if they are public member fields but with read, write and compute the value.

Is is declared like a field but with a get and set blocks inside, get is to read the property value and must return the same property type, set is to write to the property, using an implicit parameter called value.

Typically properties read and write from/to fields,

 

but we can also declare properties without depending on a field “automatic properties – introduced in C# 3.0”, when an automatic property is use, the compiler generates a private field for this property.

 

From MSDN:

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Read Only Properties:

We can make a property read-only by not adding a set accessor to the property body:

We may also mark the set accessor as private, while this will prevent class consumers from changing the property value but this doesn’t mean that this property is a read only, it just means that the property set accessor is not accessible out side this class.

… And also note, that if we started to add a body for the get accessor, we will have to add a body for the set accessor as well, which may not make sense with read only purpose properties.

We can also make the property private field a readonly, which will make sure that the field will never change after initializing.

http://stackoverflow.com/a/3917805/20126

 

Starting from C# 6.0 we can declare a read only property as an expression-bodied property

Which can contain more logic:

 

Initializing properties:

To initialize a property we can do this using the container class constructor or give the property’s private field value on deceleration.

Starting from C# 6.0 we can initialize the property inline like this:

and it can be used on read only properties as well

 

Finally, It is highly recommended to read “Why Properties Matter“!

 

examples used

Different ways to hide an HTML Element

There are different ways to hide an HTML element from the client, just hiding not removing.

We need to hide p.hide element, so the user can’t see it.

Display:

Display css property, display is the most important and most used css property to control HTML elements layout.

display:none; can be used to hide an HTML element from the view and it will appear as if it was not there on the page, means the HTML element will be hidden without blocking any space.

Example: Text 1 | Text 2 | Text 3

If we apply display:none; on Text 2, it will be: Text 1 |  | Text 3

So to hide p.hide element using display property:

Visibility:

Visibility property is the CSS property to manage HTML visibility, unlike display which has different values to control the element layout, visibility is used jut for show and hide elements

visibility: hidden can be used to hide an element from the client, but it will keep the element space visible like this: Text 1 |        | Text 3

When to use which? based on requirements and the case you have, you just need to test it on all browsers, and there will be an unrecognizable performance differences between different ways

http://stackoverflow.com/a/11757103/20126

Opacity:

Opacity property is controlling the transparency of the html element, so we can use it to make the element fully transparent and this will hide the element from the client view.

Just make sure to test it on all browsers because on older IE browsers it had some special ways to implement. (hope that no one still using old IE browsers, because you wont see many things any way 🙂 )

And the same as Visibility property, it will hide the element but will keep blocking its space, so the client will see an empty space instead of the element.

Background color and color

While it is rarely used, but we can change the background-color element css property and all child elements to be the same as the background color of the page or the same as container background.

Will need to change the text color as well to make sure that text is not visible as well.

And on some elements we may need to remove borders, that’s why this way is not common to use.

Font size:

We can hide text elements by setting font-size property to 0

Position:

Using the position property and top left we can make the control appear outside the client view.

Clip-Path (Clip):

Last way I want to mention on this post is using clip-path css property

 

 

References:

http://adaptivethemes.com/using-css-clip-as-an-accessible-method-of-hiding-content

https://snook.ca/archives/html_and_css/hiding-content-for-accessibility

http://stackoverflow.com/questions/2928688/how-to-hide-elements-without-having-them-take-space-on-the-page

http://stackoverflow.com/questions/775060/how-to-hide-the-content-of-the-div-in-css

Amazon Cloud Drive Windows Client

Amazon Cloud Drive is your place for everything digital. Cloud Drive offers free mobile apps, secure access from any computer, and it’s built in to your Amazon devices—so you can access your digital content everywhere you are.

When it comes to files hosting I trust amazon based on my previous experiences, and based on the cheap offers they have.

Also there are many file hosting web services are bases on Amazon cloud hosting and file hosting such as Dropbox which is built on Amazon S3.

So when Amazon released the Cloud drive, I signed up and started using their website, but it is not allowed to upload big files (larger than 2GB) through the website.

And for that reason I download the windows client application,

Downloaded and installed successfully on a windows 8.1 machine.

BUT: when I started to upload or download a file:

– If the file is big or trying to upload a folder, the application get closed without any error messages.

– If I am uploading a single small file an error message appear “this folder/file failed to upload”. http://screencast.com/t/RPU2kiC9SQNP

-If I am downloading a file, nothing happen, it just don’t download it.

 

On this windows 8.1 machine there are just windows defender anti virus running which is not blocking anything.

 

To solve this Issue we need to allow this application in Firewall like this http://www.wikihow.com/Add-Exceptions-to-Windows-8-Firewall

or using the following steps:

1- Open control panel

2- Windows Firewall

3- Turn windows firewall on and off

4- Select Inbound rules

5- From the right side actions click: New Rule

6- Select Program and next

7-  Browse for “C:\Users\USERNAME\AppData\Local\Amazon\Cloud Drive\AmazonCloudDrive.exe”

8- Allow connections.

9- Based on security needs select from or all “Domain”, “Private” and “Public”

10- Add a name, something like “Amazon Cloud Drive Rule” and finish

11- Go to Outbound Rules

12- Do the same as we did for Inbound Rules starting from point #5

 

These steps will make a rule in your Firewall to allow Amazon Cloud Drive to upload and download files.

Now start uploading/downloading files and It should work.

 

Also I believe that others may face the same issue because of their antiviruses and should create an exception rule to allow this application.

Integrate OpenAuth/OpenID with your existing ASP.NET MVC4 application

In this blog I am going to talk about how to integrate OpenAuth/OpenId with your existing asp.net mvc4 application in Visual studio 2012

Step 1: Create a new project

Go to File –> New Project –> Web –> Empty Asp.Net MVC 4 Application

Step 2: Add the following libraries

  • Use Nuget to get the following packages
    • DotNetOpenAuth.AspNet
      • This package is the core package for OAuth/OpenID protocol communication
    • Microsoft.AspNet.Providers.Core
      • This package brings in Universal Providers
    • Microsoft.AspNet.Providers.LocalDb
      • This package sets the connectionstring for the Universal Providers
    • Microsoft.AspNet.Membership.OpenAuth
      • This package provides the extension to integrate OAuth/OpenID with Membership providers

Step 3: Change web.config to use formsauthentication

Step 4: Adding AuthConfig

Add a new class called AuthConfig.cs to folder App_Start that class will contains the register functions for all services that we will integrate

Add the following code to AuthConfig.cs and don’t forget to get services Api keys from each service website

Register AuthConfig to application start Go to Global.asax and add the following line to Application_Start function

Step 5: Adding Login functionality

Add a new controller for Authentication functionality called it AuthController.cs
add Logon Action for login page

as you can notice that we user OAuthWebSecurity.RegisteredClientData as a model that object will contain all registered services that we put at AuthConfig class. Add a markup for login page

as you can notice that we are looping against the services that we already registered in a previous step each AuthenticationClientData represent a service so we create a button to call that service we are adding all the buttons inside single form that calling ExternalLogin action method

add ActionMethod ExternalLogin

as you can notice its a void action. we are using OAuthWebSecurity.RequestAuthentication this function is requesting the authentication from the requested provider service “Facebook – Twitter – etc.” then it returned to The URL to return to when authentication is successful. we are mentioned “ExternalLoginCallback” as a returned back action

First: we have to verify authentication to ensure that the account is successfully authenticated if not redirect users to ExternalLoginFailure action if user is authenticated then we are going to login user to the system using simple membership we are going to talk about that in later posts then check if the current user is logged in add the new account else user is new, ask for their desired membership name then redirect to ExternalLoginConfirmation action with user information at RegisterExternalLoginModel class

RegisterExternalLoginModel

Finally: your application is ready to give it a test

You can download a sample from here

Google Charts with MVC3

In this blog I am going to talk about how to add the powerfull Google Charts to your asp.net MVC 3 Application. Google Chart Tools provide a perfect way to visualize data on your website. From simple line charts to complex hierarchical tree maps, the chart galley provides a large number of well-designed chart types. Populating your data is easy using the provided client- and server-side tools.

Step 1: Create a new project

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application

Step 2:Javascript files and libraries

add the following javascript files to head of your page

Step 3: Add Client Javascript and Html

Note here we are making an ajax request to “/Home/GetData” to get data from server and assign data to google chart api

Step 4: Add ServerSide

That’s all. You can download the sample from here

Working examples using Signalr and asp.net MVC3

In this tutorial  I am going to talk about a real examples that we need to implement in most of projects.

Step 1: Create Application

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application “Internet Application” (Make sure it’s .Net Framework 4).

Step 2: Add SignalR Package

Right click on references and click Manage NuGet Packages. Search for SignalR and click install. Or use NuGet package manager concole and install the SignalR package using

Step 3: Add Hub

Create a new Class named Chat in a new folder in the solution “Name it as u want”

Note the attribute HubName above the class name, that attribute is for naming the hub during calls as we going to see later

Step 4: Add Sending Functions

You can notice that the function has three parameters a required parameter message,two optional parameters clientId and group so if we need to send message to all users live in the application we can send only message to send function and leave, if we need to send message to only one user all we have to do is to add client id with message if we want to send a message to a specific group send group name with message only

Step 5: Change user Id

the main problem for us now is the client id, Because it is changeable with each single request to the page so we need to identify users so we can add to helpers the following helper class that will help us to resetting the connection id in hub

because i am using membership to login and security i used membership.GetUser function to get user id. Remember id here is a Guid so if you are using your own implementation and not using membership you have to generate a unique Guid id for each person.

Step 6: Register new user id to Application

Now we have to register the newly generated user id to the application we are going to add the following code in Global.asax

Now in application start and while user opened a new session to your application the new Id we just made will be assigned to him and we can ue it to identify each user and send.

Step 7: Adding user to group

To add user to group i used action method in my HomeController to do that work

Step 8: Add client code

Append javascript references to the head of the page as follows

As you can notice there is a /signalr/hubs file included but its not in the project because its dynamically generated file in run time

Append the following javascript

I added commented lines above each line to declare how it works.

Append the following Html to your page

You can download the sample code from here

Creating RSS feed in ASP.net mvc3

In this toturial we are going through steps to create rss feed from a list of items using .NET’s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields.

  1. Create an empty mvc3 application and name it “RSSFeed.Website” then add Home controller.
  2. Create a class and name it NewsItem  this class we will be used as a model for retrieving feed data from the database “i will fill it manually in a the next step ”
  3. Optional step, Fill in NewsItem list if you have items in database so there is no need to fill the list like that you can get the data from the database and return it in a list of items
  4. We have to build our FeedResult class
  5. We almost done we have to create our rss page so we are going to create an ActionResult called NewsRss in HomeController
  6. we are done now except just putting a link to home to open up our RSS

You can download a sample from here

 

nopcommerce: How to get Role Name from applied discount coupon?

– Create a discount from the cms admin

– Add  a requirement for that discount and select “Must be assigned to customer role” and choose a role.

The next steps can be done anywhere in the website, I will use the CommonController to show the role name inside the website header beside the user email

–  Go to CommonController  and inside the HeaderLinks method add these lines:

So the method will look like this

 

– You will need to declare the _discountService, so declare it in the Fields region

and then initialize it in the controller constructor:

– Add DiscountRoleName property inside the HeaderLinksModel

– Inside the HeaderLinks view, inside the IsAuthinticated check, add this:

– Login to the store and apply a coupon code you just created, you will see the role name of this applied discount coupon in the header. 

Quartz.net Schedulling Jobs

Introduction:

Sometimes when you develop an application, you are going to face some tasks needs to perform a certain action at a given time without any user interaction, example for that a User wants to set an alert in specific time to remind him with a date Or something else like updating records in database periodically. All this tasks needs non-human interaction, so how could you tell the machine to do this job ? that’s the question. Cron Job is the solution for this tasks. Quartz.net has presented an excellent open source job scheduler that can be used for these purposes.

What is Quartz ?

Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term “job scheduler” seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we use this term, but in short, a job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.

Job , Schedule & Trigger:

At the beginning we have to recognize how the Quartz works. Jobs are Scheduled to run when a given Trigger occurs. Triggers can be created with nearly any combination of the following directives:

  • at a certain time of day (to the millisecond)
  • on certain days of the week
  • on certain days of the month
  • on certain days of the year
  • not on certain days listed within a registered Calendar (such as business holidays)
  • repeated a specific number of times
  • repeated until a specific time/date
  • repeated indefinitely
  • repeated with a delay interval

Quartz in Action:

Let’s go inside the code and see how Quartz works. First we will create a new Console application and get Quartz.net from Nuget Packages.

Now create a new class let’s name it MyJob, this class will be the job that we want it to be done in specific time, as we mention above it has to inherit from IJob interface.

Back to the Program.cs class in the Main method we are going to Schedule our Job with a Trigger as we said above.

Let’s explain our code. in the first two lines of code we are instantiating the Schedule which will going to register our job in it.

After that we will specify what time we want this job to run. The DateBuilder class is responsible to create our DateTimeOffset which will meet our need.

This line means that we want our Job to run at the beginning of the next minute. And now we have to build our Job by using JobBuilder class.

Here we are building a job and specify a name for this job – “job1- ” and group name – “group1”.

JJobs and Triggers are given identifying names as they are registered with the Quartz.NET scheduler. Jobs and triggers can also be placed into ‘groups’ which can be useful for organizing your jobs and triggers into categories for later maintenance. The name of a job or trigger must be unique within its group – or in other words, the true identifier of a job or trigger is its name + group. If you leave the group of the Job or Trigger ‘null’, it is equivalent to having specified SchedulerConstants.DefaultGroup.

After that we have to create Trigger for this job by using TriggerBuilder class.

Here we are saying to the trigger to start this job at the time which we were specifying before.

And then just we will schedule our job and start it. Notice that there is a line of code

this line is just to ensure that a minute will pass, because in our example we want the job to run at the beginning of the next minute. So this line is related to our example not always required.

At last we shut down the schedule. This was a simple example for Quartz.net, I’ll let you discover the whole features in this great library.

References

Quartz.net

FAQs

Download Sample

 

Using Signalr with Asp.net MVC to create simple chat application part II

As we mentioned in the previous example here, we can create a simple asynchronous actions with the signalr library like chat, real-time streaming and so on. in this blog i am going to go with another library from signalr its PersistentConnection. A PersistentConnection is the base class that has an api for exposing a SignalR service over http.

we are going to complete in the the previous application we created

Step 1:Add AdvChatController

we are going to create a new controller called AdvChatController with two action methods Index and Adv. then add index view

Step 2: Create Signalr PersistentConnection

Create a class the derives from PersistentConnection

Step 3:Setup Routing

Make a route for your connection in Global.asax

If you are setting up other routes, the SignalR mapping needs to be done before the other ones.

Step 4: Adding receiving functionality in MyConnection

Add the following functions to MyConnection class

here as you notice we can manage the users that are connected to server first on connect action that action will be called when the user connects to the application so we can add the user to a certain group also on disconnect action that action will be called when user leaves the page so we can remove the user from group. also on received function to perform the sending action to certain group

step 5: Adding Client code

Append javascript references to the head of the page as follows

Append the following javascript

Append the following Html to your page

that’s all you can now run the application now in multiple browsers and test it

You can download the sample from here