C# – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Send SMS using C# application /send-sms-using-c-application/ /send-sms-using-c-application/#comments Thu, 31 Mar 2016 12:22:25 +0000 /?p=540 Introduction

In this article I will be sharing a quick and an interesting way to send SMS using a simple C# application. I will be using ViaNett API to send messages from my application. I will be creating a simple windows form which will trigger the API and send the SMS.
Sending SMS has become a common objective for almost every site nowadays. Though they keep irritating you with continuous messages regarding their advertisements.
1
We use a simple REST API which provided by various providers in the market. You can try out some of them using the free trial version and send SMS. The reliable and faster one can be chosen. Also check for the Support the team provides.
I have thrown my hands at ViaNett and Twilio APIs. Here I will be discussing using ViaNett. Let’s start without actually wasting time.

Get Started

To start with, visit the ViaNett website (ViaNett Free demo Account). Sign up and register you with your email address for the free account, which will provide you with 5 free SMS.
After that, you land on a page having contents like below
2
Click on the Technical Api and that will navigate to different kinds of API it provides. We here would need the HTTP API in order to send the SMS, as we would be using the WebClient in order to use the API. We will be seeing the code below.
After you click on the HTTP API, you will be navigated to another page which will have the API listed under an Example like below:

Create a script to generate a URL like this: https://smsc.vianett.no/v3/send.ashx?src=xxxxx&dst=xxxxx&msg=Hello+world&username=xxxxx&password=xxxxx Retrieve this web page from your script/application, and the SMS will be sent.

This is the API URL which our Web client will be using.
Now to start with our demo application, we will be creating a windows form application. Now, I will not be writing up and lengthing my article with the step by step image for creating a Windows Form application. Those who are really new to windows form, please follow one of the best links below.
Walkthrough To create Windows Form application
After you create a simple windows form application, it would look something like below:
3
Create as simple as you can , as this is just for learning purpose. The UserName is the user name you had provided during the ViaNett registration i.e. the email address
The password is the password you had given during the registration in the ViaNett.
Then for the button click we have the following code:

private void button1_Click(object sender, EventArgs e)
        {
            using (var web = new System.Net.WebClient())
            {
                try
                {
                    string userName = txtUserName.Text;
                    string userPassword = txtUserPassword.Text;
                    string msgRecepient = txtPhNumber.Text;
                    string msgText = txtMessage.Text;
                    string url = "https://smsc.vianett.no/v3/send.ashx?" +
                        "src="+msgRecepient +
                        "&dst="+msgRecepient +
                        "&msg="+System.Web.HttpUtility.UrlEncode(msgText,System.Text.Encoding.GetEncoding("ISO-8859-1")) +
                        "&username=" + System.Web.HttpUtility.UrlEncode(userName) +
                        "&password="+userPassword;
                    string result = web.DownloadString(url);
                    if(result.Contains("OK")){
                        MessageBox.Show("Sms sent successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else{
                        MessageBox.Show("Some issue delivering","Message",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    
                }
            }
        }

The above code would look simple rather it is. 😛

When you select a Windows Form Application, by default System.Web  is not added to the reference list. Thus, you need to add that from the assembly list.

System.Web is required as we add the WebClient to use the API and download the response.

Here in the code, just giving a brief on what this snippet intends:

We retrieve each text input from the user, i.e. the User name, User password, Text Message & the User Phone Number. We use these as the URL params to the Service API of the ViaNett.

Then after that we will check for the response after sending the message and accordingly we update the User.

**Point to note is: The country code needs to be prefixed to the phone number, in order to send the message else it will mail back regarding the failure to the registered email.

Conclusion

Thus, this is a small article on the integration and sending SMS using C# aaplication. I hope this helps beginners!! I will come up with more articles with other APIs and their other SMS features they support.

References

ViaNett

]]>
/send-sms-using-c-application/feed/ 5
Sart with C# from scratch- Part 1 /sart-with-c-from-scratch-part-1/ /sart-with-c-from-scratch-part-1/#respond Sun, 15 Feb 2015 10:17:29 +0000 /?p=255 Topics to be covered:-
  • Welcome to C#
  • Working with Variables, Operators & Expressions
  • Understanding your first C# program

Welcome to C#

C# .NET is a powerful language, which is generally called Component Oriented Language. Now we have heard of Object Oriented Language, but what is component oriented language!! Though the difference is fairly blurr and thin, but the reason why this new concept came associated with C# is that a new technique was to be introduced that would develop software combining some pre-existing features (OOP) and welcoming some new components. Some of the components are :

  • Properties
  • Methods
  • Events
  • Attribute(Metadata-Data about Data)
  • Assemblies/Packages

Another major characteristic is introduction to SOC and SOA. SOC is separation of concern via partial classes in c# and SOA is service oriented architecture concept while programming in C#.

Versions in C#

I am mentioning below the versions till date. Data issued from C# Indepth. Please visit or follow the book to know more about the different Versions.

  • C#- version 1
  • C#- version 2: As mentioned, in this version, Generics, Nullable types(), anonynous types & Iterators(blocks) were introduced.
  • C#- version 3: As mentioned implicit typing, object and collection initializers, anonymous types, automatic properties, lambda expressions, extension methods, query expressions were introduced.
  • C#- version 4: As mentioned dynamic typing, optional parameters, named arguments, and generic variance were introduced.
  • C#- version 5: As mentioned asynchronous functions, caller info attributes(This is a very new concept and an interesting one too. These attributes track information about the calling methods/properties and many more.), and a tweak to foreach(one of the example is Parallel.Foreach(with Lambda expression)) iteration variable capture were introduced.

A small incident to share, I always wondered why C sharp?? It is kind of a successor for C++ or what? I always wondered, and I feel many beginner developers would be wondering. Thanks to Wiki the datawarehouse for every bit of concept in the world for letting me know why? Without any delay, straight from the WIKI,

The name “C sharp” was inspired by musical notation where a sharp indicates that the written note should be made a semitone higher in pitch. The sharp symbol also resembles a ligature of four “+” symbols, which thus implies that it is an increment of C++.

Now lets get along and start learning from basics.

Camel & Pascal Case Notations

Every time a developer gets into these concepts, but sometimes beginners like me would wonder what these actually are!!.
Camel case are used for naming fields where as Pascal case are used for naming properties, function names. In Pascal case, the starting letters in the multiword name are capitalized where as in Came case except the very frst letter all are capitalized like below:

  • Pascal Case:- GetSumFromNumbers
  • Camel Case:- getFirstNumber

Working with Variables, Operators & Expressions

Before getting into the variables, lets get into what is an identifier. Identifiers are the names that are used to identify elements in the program. In C#, there are certain conventions to be followed:

  • Only letters are allowed(may it be uppercase or lowercase), digits and underscore(_) characters are allowed.
  • An identifier should always start with a letter.

For example, _getSum, GetSum, Get_sum are valid identifiers. Just to remember or keep in mind everytime that C# is case sensitive so getSum and GetSum are different and give different meanings.
Keywords, there are many keywords that are predefined in C#, for more info on the keywords, follow the below link: C# keywords

Now lets get back to our topic of discussion, variables. A variable is a location with memory or storage location that stores/holds a value. A variable in a program holds a unique name, its like madatory to give it a unique name. A variable holds temporary information. A variable is used to get the value that it holds after assigning. Below I specify the naming conventions to be followed while declaring variables specified by Microsoft .NET team:

  • Underscores are advised not to be used
  • Case differing names for variables should be avoided. Like, abcTest or AbcTest to be used in the same file and same time. This would also mean Identifiers with same name and different case should be avoided.
  • It is advised to start the name with a lowercase. This would be consistent through out as it would lead to easy mantenance.
  • Camel case notations should be used, forexample, abcTest, myVariable, as such.

Declaring Variables is easy and simple. Usually keyword var is used when the type is to be implicitly decided. If any datatype is already used during declaring the vriable, then it is explicitly typed.

var setAge; //implicitly typed
int setAge; //explicitly typed
setAge = 45; //values assigned

As in the above peice of snippet, you can see the statement ends with a semicolon “;” that as simple marks the end or compiler to know that the statement ends here. Equals operator is used to assign the value to the declared variable. C# also uses same the operators that we as developers have been using in the former programming languages (+(plus), -(subtraction), *(asterix/multiplication), /(divide) and also the modulo operator(%)). These are as we know called the arithmetic operators. We cannot apply the arithmetic operations on the datatypes except int(integer type) in a similar way.

int a = 4 + 3;
string b = "4"+"3";
Console.Writeline(a);//Prints 7
Console.Writeline(b);//Prints 43 not 7

However using explicit conversion, string can be converted into integers. For incrementing the values, the increment and decrement operators are also strongly followed in C#.

count= count + 1; //Can be incremented but should not be written like this
count++; //This is how increment should be done

count = count - 1;
count = count--;

Understand your first C# program

As we all know, every program follow a common rule that is Input, Process & Output. Lets have go at it.

using System;
namespace ConsoleDemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName; //Variable for storing string value
            string lastName;

            //Displaying message for entering value
            Console.WriteLine("Please Enter Your First Name");
            //Accepting and holding values in name variable
            firstName = Console.ReadLine();

            Console.WriteLine("Please Enter Your Last Name");
            lastName = Console.ReadLine();

            //Displaying Output
            //{0}{1} take the variable names that are assigned during the runtime by the user
            Console.WriteLine("Welcome {0} {1} in your first C-sharp program", firstName,lastName);

            //Holding console screen
            Console.ReadLine(); 
        }
    }
}

When we run the above program, we get the below output. I am showing the output step wise, so that you get to know the importance of the Console.WriteLine & Console.ReadLine

.output1 As we see in the image, the console window opens up when the project runs and asks for the first name as we see in the program first comes Console.WriteLine(), then when user enters the name Console.ReadLine(), plays its role and stores it in the variable memory firstName.

output2 As we see in the image, the console window opens up when the project runs and asks for the last name as we see in the program first comes Console.WriteLine(), then when user enters the name Console.ReadLine(), plays its role and stores it in the variable memory lastName.

output3  Now when a final enter is pressed by the user with curosity to know what the program gives! Yes it gives the desired out put. It concats the variables where the names/values entered by the user are temporarily stored in memory. {0} {1}, this actually contain the values entered by the user when asked and as mentioned concats the input and displays the full name as the output. This could also have been achieved by using the “+” operator like: 

string fullName = firstName + " " + lastName; //+ operator concats the strings
Console.WriteLine("Welcome {0} in your first C-sharp program", fullName);

There are many libraries that may be used in your program. These libraries need to be mentioned at the top of your program i.e. which is called Namespaces and they are used using a using keyword. 😀 Yes so many use…!!

When on the console window, something needs to be displayed, Console.WriteLine() is used and when we need to take the Input from the user and store in memory, Console.ReadLine() is used. This is a simple and basic difference. The {0} used in our program, acts as asimple placeholder where the dynamic values are used by specifying the argument at the end. The many the arguments, the many the placeholders to be used.

Conclusion

Thanks guys for having patience and reading through. This is what I could cover in the first part and will continue some more interesting topics in the second part. Lets learn Lets explore and Lets share…

Any suggestions and corrctions are humbly accepted as we all keep learning at every step.
Follow the C# 6 New Features for more info on the upcoming version C# 6.

Refrences

CP

]]>
/sart-with-c-from-scratch-part-1/feed/ 0