C# Variable

Example: C# Variable

namespace CSharpTutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hello World!!";

            Console.WriteLine(message);
        }
    }
}

The variable in C# is nothing but a name given to a data value. In the above example, message is the name of the variable that stores the string data value “Hello World!!”. As the name suggests, the contents of a variable can vary, i.e., you can change the value of a variable at any time.

In C#, a variable is always defined with a data type. The following is the syntax variable declaration and initialization.

Variable Syntax:
<data type> <variable name>;

<datatype> <variable name> = <value>;

A variable can be declared and initialized later or it can be declared and initialized at the same time. In the following example, the first statement declares a variable called “message” without assigning any value to it. In the second statement, a value is assigned to the “message” variable.

Example: Variable Declaration
string message;

// value can be assigned after it declared 
message = "Hello World!!";

In the following example, variable is declared and initialized (a value is assigned to it) at the same time.

Example: Variable Declaration & Initialization
string message = "Hello World!!";

Multiple variables of the same data type can be declared and initialized in a single line separated by commas.

Example: Multiple Declarations
int i, j, k, l = 0;

int amount, num;

When declaring multiple variables of the same data type, you can put them in multiple lines for the sake of readability; even if split across multiple lines, the compiler will consider it to be one statement, until it encounters a semicolon (;).

Example: Multi-Line Declarations
int i, j, 
    k, 
    l = 0;

The value of a variable can be assigned to another variable of the same data type. However, a value must be assigned to a variable before using it.

Example: Variable Assignment
int i = 100;

int j = i; // value of j will be 100

The following example would give a compile time error because string value cannot be assinged to a int type variable.

Example: Invalid Variable Assignment
string message = "Hello World!!";

int i = message; // compile time error

You must assign a value to a variable before using it otherwise the compiler will give an error. For example, in the following code, we have declared a variable called i without assigning any value to it. If we then try to display the value of the variable on the console, we will get a compile time error.

Example: Invalid Variable Assignment
int i;

//Following will give compile time error: "Use of unassigned local variable 'i'"
int j = i;
Console.WriteLine(j); 
 Points to Remember :
  1. The variable is a name given to a data value.
  2. A variable holds the value of specific data type e.g string, int, float etc.
  3. A variable can be declared and initialized in separate statements and also in the single statement.
  4. The value of a variable can be changed at any time throught out the program as long as it is accessible.
  5. Multiple variables can be defined seperated by comma (,) in a single or multiple line till semicolon(;).
  6. A value must be assigned to a variable before using it otherwise it will give compile time error.
Please follow and like us:

First C# Hello World Program

Every console application starts from the Main() method of Program class. The following example code displays “Hello World!!” on the console.

Example: Simple Console Project with C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace CSharpTutorials
{
    class Program
    {
            static void Main(string[] args)
        {
            string message = "Hello World!!";
            Console.WriteLine(message);
        }
    }
}

The following image illustrates the important parts of the above example.

Let’s understand the above C# structure.

  1. Every .NET application takes the reference of the necessary .NET framework namespaces that it is planning to use with the “using” keyword e.g. using System.Text
  2. Declare the namespace for the current class using the “namespace” keyword e.g. namespace CSharpTutorials.FirstProgram
  3. We then declared a class using the “class” keyword: class Program
  4. The Main() is a method of Program class which is the entry point of the console application.
  5. String is a data type.
  6. ‘message’ is a variable, that holds a value of a specified data type.
  7. “Hello World!!” is the value of the message variable.
  8. Console is a .NET framework class. WriteLine() is a method which you can use to display messages to the console.
 Note:
Every line or statement in C# must end with a semicolon (;).

Compile and Run C# Program

In order to see the output of the above C# program, we have to compile it and run it by pressing Ctrl + F5, or clicking Run button or by clicking the “Debug” menu and clicking “Start Without Debugging”. You will see following output in the console:

Output:
Hello World!!
Please follow and like us:

C# Access modifiers

Access modifiers are applied on the declaration of the class, method, properties, fields and other members. They define the accessibility of the class and its members.

Access Modifiers Usage
public The Public modifier allows any part of the program in the same assembly or another assembly to access the type and its members.
private The Private modifier restricts other parts of the program from accessing the type and its members. Only code in the same class or struct can access it.
internal The Internal modifier allows other program code in the same assembly to access the type or its members. This is default access modifiers if no modifier is specified.
protected The Protected modifier allows codes in the same class or a class that derives from that class to access the type or its members.
Please follow and like us:

C# Version History

C# is a simple & powerful object-oriented programming language developed by Microsoft.

C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0 and the current version of C# is 6.0.

The following table lists important features introduced in each version of C#:

Version Important Features
C# 1.0
  • Basic features
C# 2.0
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Covariance and Contra-variance
  • Static classes
C# 3.0
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
C# 4.0
  • Dynamic binding (late binding)
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types
C# 5.0
  • Async features
  • Caller information
C# 6.0
  • Expression Bodied Methods
  • Auto-property initializer
  • nameof Expression
  • Primary constructor
  • Await in catch block
  • Exception Filter
  • String Interpolation
C# 7.0
  • out variables
  • Tuples
  • Discards
  • Pattern Matching
  • Local functions
  • Generalized async return types
  • throw Expressions
Please follow and like us:

C# – Get Started

C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on the C# language and the .NET Framework.

And here in developersportal.net we are going to post a C# tutorials that will help you learn the essentials of C#, from the basic to advance level topics.

These tutorials are designed for beginners and professionals who want to learn C# step-by-step.

Add Developersportal.net to your favorite and follow us on our Facebook page.

Please follow and like us:

How To Create  multiple site collections with new content databases 

To Create  multiple site  collections with new content databases , follow the bellow steps

1-  create web application  ex:   http://Developersportal.net

2 – from application management > manage web application

3 – select your web app and go to managed path

4 – inter the path and from type combo box select “Explicit inclusion” ex: http://Developersportal.net/Sharepoint

5 – create new content database using SharePoint management shell (run as admin)

 

New-SPContentDatabase -Name wss_Content_SharePoint-WebApplication http://Developersportal.net
6 - create the new site collection by running the bellow powershell script

$url = "http://Developersportal.ner/Sharepoint"
$ContentDatabase = "wss_Content_SharePoint"
$WebsiteName = "Sharepoint"
$WebsiteDesc = "Sharepoint site"
$Template = "STS#1"
$PrimaryLogin = "developersportal\sp_farm"
$PrimaryDisplay = "sp_farm"
$PrimaryEmail = "admin@developersportal.net"

New-SPSite -Url $url 
–ContentDatabase $ContentDatabase 
-Name $WebsiteName 
–Description $WebsiteDesc  
-Template $Template 
-OwnerAlias $PrimaryLogin 
–OwnerEmail $PrimaryEmail


Enjoy your new site collection

Please follow and like us:

It’s official: Microsoft has acquired GitHub for $7.5 billion

After much speculation, Microsoft has confirmed its acquisition of the social coding platform Github in an all-stock deal worth $7.5 billion.

The acquisition is expected to close by the end of the year, subject to regulatory approval.

As part of the purchase, Microsoft is installing a new CEO. Former Xamarin chief Nat Friedman will replace the outgoing GitHub CEO and co-founder, Chris Wanstrath. Microsoft says that Wandstrath will join the company as a technical fellow.

The deal is unlikely to change the day-to-day running of GitHub. Microsoft says that the service will continue to run independently, and will retain its “developer ethos.”

This story is developing.

Please follow and like us:

Basic Operation’s That SharePointer Needs For SharePointing By Using CSOM – Part 4

SharePoint user tasks

You can use the SharePoint .NET Framework CSOM to manage SharePoint users, groups, and user security.

Add a user to a SharePoint group

This example adds a user and some user information to a SharePoint group named Members.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

GroupCollection siteGroups = context.Web.SiteGroups; 

// Assume that there is a "Members" group, and the ID=5. 
Group membersGroup = siteGroups.GetById(5); 

// Let's set up the new user info. 
UserCreationInformation userCreationInfo = new UserCreationInformation(); 
userCreationInfo.Email = "user@domain.com"; 
userCreationInfo.LoginName = "domain\\user"; 
userCreationInfo.Title = "Mr User"; 

// Let's add the user to the group. 
User newUser = membersGroup.Users.Add(userCreationInfo); 

context.ExecuteQuery();  

Retrieve all users in a SharePoint group

This example retrieves information about all users from a SharePoint group named Members.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

GroupCollection siteGroups = context.Web.SiteGroups; 

// Assume that there is a "Members" group, and the ID=5. 
Group membersGroup = siteGroups.GetById(5); 
context.Load(membersGroup.Users); 
context.ExecuteQuery(); 

foreach (User member in membersGroup.Users) 
{ 
    // We have all the user info. For example, Title. 
    label1.Text = label1.Text + ", " + member.Title; 
}  

Create a role

This example creates a role that has create and manage alerts permissions.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

BasePermissions perm = new BasePermissions(); 
perm.Set(PermissionKind.CreateAlerts); 
perm.Set(PermissionKind.ManageAlerts); 

RoleDefinitionCreationInformation creationInfo = new RoleDefinitionCreationInformation(); 
creationInfo.BasePermissions = perm; 
creationInfo.Description = "A role with create and manage alerts permission"; 
creationInfo.Name = "Alert Manager Role"; 
creationInfo.Order = 0; 
RoleDefinition rd = context.Web.RoleDefinitions.Add(creationInfo); 

context.ExecuteQuery();  

Add a user to a role

This example adds a user to a role.

C#

// Starting with ClientContext, the constructor requires a URL to the

// server running SharePoint.

ClientContext context = new ClientContext("http://SiteUrl");

// Assume that we have a SiteUser with Login user.

Principal user = context.Web.SiteUsers.GetByLoginName(@"domain\user");

// Assume that we have a RoleDefinition named "Read".

RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Read"); RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);

roleDefCollection.Add(readDef);

RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection); context.ExecuteQuery();


Part 1
Part 2
Part 3

Please follow and like us:

Basic Operation’s That SharePointer Needs For SharePointing By Using CSOM – Part 3

Previously in part one we discussed the main operation that developers needs to deal with SharePoint site , and in part 2 , we talked about  SharePoint list , and the bellow examples show how to use the .NET Framework CSOM to complete list item -related tasks.

SharePoint list item tasks

These examples demonstrate how to use the .NET Framework CSOM (Client side object model) to complete tasks that are related to list items.

Retrieve items from a SharePoint list

This example retrieves the items in a SharePoint list. You also need to add a using statement for Microsoft.SharePoint.Client.QueryExpression.

Note

You can use the FolderServerRelativeUrl property to further restrict the items that are returned to those in a specified folder.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" 
// so that it grabs all list items, regardless of the folder they are in. 
CamlQuery query = CamlQuery.CreateAllItemsQuery(100); 
ListItemCollection items = announcementsList.GetItems(query); 

// Retrieve all items in the ListItemCollection from List.GetItems(Query). 
context.Load(items); 
context.ExecuteQuery(); 
foreach (ListItem listItem in items) 
{ 
    // We have all the list item data. For example, Title. 
    label1.Text = label1.Text + ", " + listItem["Title"]; 
} 

Create a new list item

This example creates a new SharePoint list item by using the ListItemCreationInformation class.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// We are just creating a regular list item, so we don't need to 
// set any properties. If we wanted to create a new folder, for 
// example, we would have to set properties such as 
// UnderlyingObjectType to FileSystemObjectType.Folder. 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = announcementsList.AddItem(itemCreateInfo); 
newItem["Title"] = "New Item!"; 
newItem["Body"] = "Hello Developers world!"; 
newItem.Update(); 

context.ExecuteQuery();  

Update a list item

This example updates a SharePoint list item.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.GetItemById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery();  

Delete a list item

This example deletes a SharePoint list item.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume that there is a list item with ID=2. 
ListItem listItem = announcementsList.GetItemById(2); 
listItem.DeleteObject(); 

context.ExecuteQuery(); } 
Please follow and like us:

basic operation’s that SharePointer needs for SharePointing by using CSOM – part 2

Previously in part one we discussed the main operation that developers needs to deal with SharePoint site and here in part 2 to we’ll focus on SharePoint list , and the bellow examples show how to use the .NET Framework CSOM to complete list-related tasks.

Retrieve all SharePoint lists in a website

This example retrieves all SharePoint lists in a SharePoint website. To compile this code, you need to add a using statement for System.Linq.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server. 
context.Load(web.Lists, 
             lists => lists.Include(list => list.Title, // For each list, retrieve Title and Id. 
                                    list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the web.Lists. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

Note

Alternatively, you can use the LoadQuery method to store the return value in another collection, rather than use the web.Lists property. You will also need to add using statements for System.Collections.Generic and System.Linq. Also, add an alias to the using statement for the Microsoft.SharePoint.Client namespace so you can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server, and put the return value in another 
// collection instead of the web.Lists. 
IEnumerable<SP.List> result = context.LoadQuery(web.Lists.Include( // For each list, retrieve Title and Id.
                                                                   list => list.Title, 
                                                                   list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the result. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

Create and update a SharePoint list

This example creates a SharePoint list and updates it by using the ListCreationInformation class.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// The SharePoint web at the URL.
Web web = context.Web; 

ListCreationInformation creationInfo = new ListCreationInformation(); 
creationInfo.Title = "My List"; 
creationInfo.TemplateType = (int)ListTemplateType.Announcements; 
List list = web.Lists.Add(creationInfo); 
list.Description = "New Description"; 

list.Update(); 
context.ExecuteQuery(); 

Delete a SharePoint list

This example deletes a SharePoint list.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// The SharePoint web at the URL.
Web web = context.Web; 

List list = web.Lists.GetByTitle("My List"); 
list.DeleteObject(); 

context.ExecuteQuery();  

Add a field to a SharePoint list

This example adds a field to a SharePoint list. Add an alias to the using statement for the Microsoft.SharePoint.Client namespace so you can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.

Note

The example uses context.CastTo to do a cast. Before executing the query, the client library does not know the real type of the returned object “field”, and SharePoint.Field is the only possible type. If you know the real type, you can use the ClientContext.CastTo method to cast the object.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

SP.List list = context.Web.Lists.GetByTitle("Articles"); 

SP.Field field = list.Fields.AddFieldAsXml("<Field DisplayName='MyField2' Type='Number' />", 
                                           true, 
                                           AddFieldOptions.DefaultValue); 
SP.FieldNumber fldNumber = context.CastTo<FieldNumber>(field); 
fldNumber.MaximumValue = 100; 
fldNumber.MinimumValue = 35; 
fldNumber.Update(); 

context.ExecuteQuery();  
Please follow and like us: