Tuesday, 31 January 2017

Get the class properties in the list

In this article you will learn, how you can access your class properties value in a list and perform whatever operation you want with the properties value.
below is my Class named Employee. this class contains four properties.

    public class Employee
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { getset; }
        public string Mobile { getset; }
    }

In the below class I'm calling a function that takes my class object and add all the property value in the list.
GetPolicyDataString function concating all values with tild "~" seprated.

   class Program
    {
        static void Main(string[] args)
        {
            Employee pi = new testGenrateString.Employee();
            pi.FirstName = "SURAJ";
            pi.LastName = "MADDHESHIYA";
            pi.Address="Berlin";
            pi.Mobile = "8527123456";
            Program p = new testGenrateString.Program();
            var val = p.GetPolicyDataString(pi);
            Console.WriteLine(val);
            Console.Read();
        }

        public string GetPolicyDataString(Employee ppInfo)
        {
            string dataString = string.Empty;
            List<string> lstString = new List<string>();
            foreach (var prop in ppInfo.GetType().GetProperties())
            {
                lstString.Add(Convert.ToString(prop.GetValue(ppInfo, null)));
            }
             dataString = string.Join("~", lstString.ToArray());

            return dataString;
        }
    }

OUTPUT


Continue Reading →

Saturday, 21 January 2017

STUFF() - SQL Server

Description:
STUFF function is used to append number of characters from one string and replace them with another string. So, you can say this function insert string into another string, it removes all the specified length of string and insert other string value on that place.

Syntax
STUFF(stringstartlengthadd_string) 

Example:
1- SELECT STUFF('dotnetguru.in',12,2, 'com') as [stuff eg]

2- SELECT STUFF('www.dotnetguru.in',1, 0, 'http://')  as [stuff eg]

Output:

1- dotnetguru.com
2- http://www.dotnetguru.in
Continue Reading →

Thursday, 19 January 2017

Basics of SQL Commands

SQL commands are a set of instructions that are used to interact with the database like Sql Server, MySql, Oracle etc. SQL commands are responsible to create and to do all the manipulation on the database. These are also responsible to give/take out access rights on a particular database

Sql Commands Category

We have different sql commands for different-different purpose. We can grouped Sql Commands into five major categories depending on their functionality.

01.       Data Definition Language (DDL)

These SQL commands are used to create, modify, and drop the structure of database objects like table, view, procedure, indexes etc. In this category we have CREATE, ALTER, DROP and TRUNCATE commands.

Note:-
1.           Only with DDL commands we need to write keyword (like table, procedure, view, index, function) with the syntax of command.
2.           These commands are used to create/modify the structure of the database object.

Example:

CREATE TABLE TABLE_NAME
(
COL1 VARCHAR(10),
COL2 VARCHAR(20),
);
--Here "TABLE" is a keyword that is used to create table "TABLE_NAME"
CREATE VIEW VIEW_NAME
AS
BEGIN
 SELECT * FROM EMP_TABLE
END
--Here "VIEW" is a keyword that is used to create VIEW "VIEW_NAME"

02.      Data Manipulation Language (DML)

These SQL commands are used to store, modify, and delete data from database tables. In this category we have INSERT, UPDATE, and DELETE commands.

03.     Data Query Language (DQL)

These SQL commands are used to fetch/retrieve data from database tables. In this category we have only SEELCT command.

04.     Transaction Control Language (TCL)

These SQL commands are used to handle changes which affect the data in database. Basically we use these commands with in the transaction or to make a stable point during changes in database at which we can rollback the database state if required. In this category we have SAVEPOINT, ROLLBACK and COMMIT commands.

05.      Data Control Language (DCL)

These SQL commands are used to implement security on database objects like table,view,stored procedure etc. In this category we have GRANT and REVOKE commands.

Note:-

Grant Command : This command is used to give permission to specific users on specific database objects like table, view etc.

Revoke Command : This command is used to take out permission from specific users on specific database objects like table, view etc.
Continue Reading →

Monday, 16 January 2017

Comma separated value parameter in SQL IN clauses

How to use comma separated values parameter in SQL IN Clause in SQL Queries-

The SQL IN clause is very useful, since it allows you to specify exactly which values you want to return.
For this tip,  let's assume we have a database with this table:

CREATE TABLE [dbo].[Employee](
 [ID] [int] NOT NULL,
 [Name] [varchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY 

And the Data is:
ID Name
1 Suraj
2 Aden
3 Richerd
4 Shekhar
5 Shankar

We can get the rows from table for whatever Id's we need
SELECT [ID] ,[Name] FROM [dbo].[Employee] WHERE Id IN (1, 3)

And we get the expected data
ID Name
1 Suraj
3 Richerd

But what, if we pass the parameter in string variable
DECLARE @ids VARCHAR(10)
SET @ids = '1,3'
SELECT [ID] ,[Name] FROM [dbo].[Employee] WHERE Id IN (@ids)

You will get the below Error:

Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the varchar value '1,3' to data type int.

So, What is the Solution

What we need to do is, convert the comma separated values into a table first. My initial version was inline, and rather messy, so I re-worked it to a user defined function and made it a bit more general purpose. 

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[CSVToTable] (@ids VARCHAR(MAX))
RETURNS @TempTab TABLE
   (id int not null)
AS
BEGIN
     -- Ensure input ends with comma
 SET @ids = REPLACE(@ids + ',', ',,', ',')
 DECLARE @SP INT
DECLARE @VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', @ids ) <> 0 
BEGIN
   SELECT  @SP = PATINDEX('%,%',@ids)
   SELECT  @VALUE = LEFT(@ids , @SP - 1)
   SELECT  @ids = STUFF(@ids, 1, @SP, '')
   INSERT INTO @TempTab(id) VALUES (@VALUE)
END
 RETURN
END
GO

This creates a user defined function that takes a comma separated value string and converts it into a table that SQL does understand - just pass it the sting, and it works it all out.

How to Use the above UDF

Example:
DECLARE @idList VARCHAR(10)
SET @idList = '1,3'
SELECT [ID] ,[Name] FROM [dbo].[Employee] WHERE Id IN (SELECT * FROM dbo.CSVToTable(@idList))

Please Share if you liked this Post.

References: Codeproject
Continue Reading →

Tuesday, 27 September 2016

Login with facebook

Here in This Article I am going to explain you how to implement Login with facebook in your website. first of all you need to create a new App in facebook developers. https://developers.facebook.com/apps/

1- Click On Add a New App button. a pop window will be open.
2- Select WWW (Website) Link.

3- Provide App Name and click on "Create New Facebook AppID" Button.

4- In the Opened pop window, Provide Display Name, Contact EmailId and Category.
     For Category Choose "Apps for Pages" option
Then Click on Create App ID button.



5-  Continue with Security Check window. Now, your app hes been created. you need to do some setting now.
6- Open the facebook apps home Page. https://developers.facebook.com/apps/
     You will see your App "socialLogin" in the list.


7- Click on your app. it'll redirect you on the new Page.


Now you have App ID and App Secret Key.

8- In the Settings menu on the left side, You can set other information's like Site Url, App logo and others.

9- Now, Go to Roles -> Test Users Option.
     Click On Add button to add a Test User.


A popup will be open. Just Click on Create Test Users button. 
A Test User will be created. see the below Image.


10- Now, Come to App Review Section.


Select the radio button to Yes. Now your App is Live to use.

11- Now, Come to Dashboard Basic Settings option. see the below.


Click On Quick Start button. it'll redirect you to the new page.
On the new Page Under Site Url Section you will see Next button. Click on the Next button. 
 A new section will be open. just Click On Login Option in that section. it'll open a new window again.

you don't need to follow the above red colored steps.


12- Copy the entire Html Code from Full Code Example Section. Create a new Html file named index.html in your any directory. Paste the Code in newly created file.

Note: for detailed knowledge please go through the Url https://developers.facebook.com/docs/facebook-login/web/

13- Open the html file and Add the AppId generated from your App.


14- You Can Change graph Api version based on your requirements. I've used 2.7.


15- Now Save your Html File. 

Now it's time to run the html. but before this you need to host your html on IIS server.

So, goto inetmgr and add a new Website. Provide Html file path and port that you have provided in facebook app and Host name as "localhost". Click on Ok button.



now browse the website from IIS.

Click On Log In button. facebook login window will be open. provide your user name and password., and click on Login button. 


Click on Continue button.

You will see your Username from facebook. now you're logged in with facebook.

Download html file here

Take more help from below video





Continue Reading →

Monday, 26 September 2016

Login With Google

Here in This Article I am going to explain you how to implement Login with Google in your website. first of all you need to create a new project in Google developers console. https://console.developers.google.com/



Select your existing project. if you haven't created then first of all Create a new Project.

Provide Project Name. I have provided "LoginWithGoogle". click on Create button.
Now Click on Credentials Link on Left Side Menu.
Click On OAuth consent screen Link and Fill the information. finally click on Save button.


It will Redirect you to the Credentials Page. 


Click on Create credentials Button. it'll open a menu. Click on OAuth client ID.



Click on Web application Radio button.



Fill the Information and Click on Create Button. It'll generate Client ID and Client Secret Key.


Finally Click On Save Button. 
Now You have Client ID and Secret Key for your Login with Google functionality.

Now come to your Visual Studio Project.
Create a new MVC Project.

In the Model Folder Create a new Model class.

  public class GoogleDataModel  
   {  
     public string Email_address { get; set; }  
     public string Google_ID { get; set; }  
     public string firstName { get; set; }  
     public string LastName { get; set; }  
     public string fullName { get; set; }  
     public string Client_ID { get; set; }  
     public string Return_url { get; set; }  
     public string userProfilePic { get; set; }  
     public string Gender { get; set; }  
   }  

In the Home Controller add the Client Key and Secret Key.

  public class HomeController : Controller  
   {  
     string clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  
     string clientSecret = "qL78qLvihhfgf9VWT189898fG9";  
     public ActionResult Index()  
     {  
       ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";  
       return View();  
     }  
     public ActionResult GetGoogleAccount()  
     {  
       return View();  
     }  
  ------
  ---------

In the Index View Add the Login Button and Some Javascript Code.

  <input type="button" id="Button1" value="Login With Google" onclick="OpenGoogleLoginPopup();" />  
  
 <script type="text/javascript" language="javascript">  
     var clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  

     function OpenGoogleLoginPopup() {  
       var url = "https://accounts.google.com/o/oauth2/auth?";  
       url += "scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&";  
       url += "state=%2Fprofile&"  
       url += "redirect_uri=http://localhost:53285/Home/GetGoogleAccount&"  
       url += "response_type=token&"  
       url += "client_id="+clientId;  
       window.location = url;  
     }  
   </script>   

Now, In the GetGoogleAccount View Add the Below Code.

 @{  
   ViewBag.Title = "GetGoogleAccount";  
 }  
 <script type="text/javascript">  
   try {  
     debugger;  
     // First of all, parse the querystring  
     var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;  
     while (m = regex.exec(queryString)) {  
       params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);  
     }  
     var ss = queryString.split("&")  
     if (ss != undefined) {  
       window.location = "About?" + ss[1];  
       history.pushState("", "", "About");  
     }  
     else  
       window.location = "About";  
   } catch (exp) {  
   }  
 </script>  

Now, In the About Action add the below Code.

  public ActionResult About()  
     {  
       GoogleDataModel model = new GoogleDataModel();  
       if (Request.QueryString["access_token"] != null)  
       {  
         string test = Request.QueryString["access_token"];  
       }  
       if (Request.QueryString["access_token"] != null)  
       {  
         String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();  
         WebClient webClient = new WebClient();  
         Stream stream = webClient.OpenRead(URI);  
         string b;  
         /*I have not used any JSON parser because I do not want to use any extra dll/3rd party dll*/  
         using (StreamReader br = new StreamReader(stream))  
         {  
           b = br.ReadToEnd();  
         }  
         b = b.Replace("id", "").Replace("email", "");  
         b = b.Replace("given_name", "");  
         b = b.Replace("family_name", "").Replace("link", "").Replace("picture", "");  
         b = b.Replace("gender", "").Replace("locale", "").Replace(":", "");  
         b = b.Replace("\"", "").Replace("name", "").Replace("{", "").Replace("}", "");  
         /*  
         "id": "109124950535374******"  
          "email": "usernamil@gmail.com"  
          "verified_email": true  
          "name": "firstname lastname"  
          "given_name": "firstname"  
          "family_name": "lastname"  
          "link": "https://plus.google.com/10912495053537********"  
          "picture": "https://lh3.googleusercontent.com/......./photo.jpg"  
          "gender": "male"  
          "locale": "en" }   
         */  
         Array ar = b.Split(",".ToCharArray());  
         for (int p = 0; p < ar.Length; p++)  
         {  
           ar.SetValue(ar.GetValue(p).ToString().Trim(), p);  
         }  
         model.Email_address = ar.GetValue(1).ToString();  
         model.Google_ID = ar.GetValue(0).ToString();  
         model.firstName = ar.GetValue(4).ToString();  
         model.LastName = ar.GetValue(5).ToString();  
         model.fullName = model.firstName + " " + model.LastName;  
         model.Gender = ar.GetValue(8).ToString();  
         model.userProfilePic = ar.GetValue(7).ToString();  
         model.userProfilePic = model.userProfilePic.Replace("https", "https:");  
       }  
       return View(model);  
     }  

Add the Code in About.cshtml

 @model LoginWithFbDemo.Models.GoogleDataModel  
 @{  
   ViewBag.Title = "About";  
 }  
   <div id="ClientDetails">  
   <br ><br >  
     @Html.TextBoxFor(x=> x.fullName)  
   @Html.TextBoxFor(x=> x.Email_address)  
   <img id="imgProfile" src="@Model.userProfilePic" style="width:auto"/><br >  
   </div>  

Now you're done. Run the Application.


 Click On Login With Google Button.


Provide the Email Id and Password. Click on Sign In Button.

It'll ask the Permission. Click on Allow button.


It will redirect you to the About Page. You will see your Name, Email Id and Profile Pic.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives