Search This Blog

Tuesday, June 13, 2017

Create WCF Service in C# using SQL server

Newtonsoft.Json :

This DLL  download and Reference in project  .

Web.config :

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="NGOConnectionString" value="Data Source=11.111.43.65;Initial Catalog=DB_NGO;User ID=NGO;Password=NGO"/>
    <add key="NGOConnectionString" value="Data Source=45.45.45.45;Uid=ngo;Pwd=ngo;Initial Catalog=ngo_LOG"/>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
    <authentication mode="Forms"/>
    <identity impersonate="true"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="NGOAutomateServices.NGOITISGServices" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" address="" contract="NGOAutomateServices.INGOITISGServices" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>
    <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
</configuration>

Add New Folder “Classes ” Paste Support Classes  In this Folder

1 - clsSQLHelper.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Xml;

namespace NGOAutomateServices.Classes
{
    public class clsSQLHelper
    {
        #region "Private Members"

        private SqlConnection _connection;
        private SqlTransaction _transaction;

        private bool _disposed;

        private static HttpServerUtility _httpServer;
        private static string _applicationName;

        private static bool _applicationDebug;
        private static string _logFolder;
        private static string _tempFolder;
        private static string _reportFolder;
        private static string _logFolderAbsolute;
        private static string _tempFolderAbsolute;

        private static string _reportFolderAbsolute;
        private static string _dbServerName;
        private static string _dbName;
        private static string _dbUser;
        private static string _dbPassword;

        #endregion

        #region " Constructors "

        private clsSQLHelper()
        {
            _disposed = false;
        }

        public clsSQLHelper(string ConnectionString)
            : this()
        {
            _connection = new SqlConnection(ConnectionString);
        }

        #endregion

        #region " Private Methods "

        private SqlCommand GetNewCommand(string SQLCommand, CommandType SQLType)
        {
            SqlCommand cmd = new SqlCommand();

            OpenConnection();
            cmd.CommandText = SQLCommand;
            cmd.CommandType = SQLType;
            cmd.Connection = _connection;
            cmd.CommandTimeout = 60;

            // Apply transaction if required
            if (this.IsTransaction)
            {
                cmd.Transaction = _transaction;
            }

            return cmd;
        }

        private SqlCommand GetNewCommand(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            SqlCommand cmd;

            cmd = GetNewCommand(SQLProcedureName, CommandType.StoredProcedure);

            if ((SQLParameters != null) && SQLParameters.Length > 0)
            {
                foreach (SqlParameter param in SQLParameters)
                {
                    cmd.Parameters.Add(param);
                }
            }

            return cmd;
        }

        private void OpenConnection()
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
        }

        private void CloseConnection()
        {
            if (!this.IsTransaction)
            {
                _connection.Close();
            }
        }

        private int ExecuteNonQuery(ref SqlCommand cmd)
        {
            try
            {
                return cmd.ExecuteNonQuery();
            }
            finally
            {
                CloseConnection();
                cmd.Dispose();
                cmd = null;
            }
        }

        private SqlDataReader ExecuteReader(ref SqlCommand cmd)
        {
            try
            {
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            finally
            {
                cmd.Dispose();
                cmd = null;
            }
        }

        private object ExecuteScalar(ref SqlCommand cmd)
        {
            try
            {
                return cmd.ExecuteScalar();
            }
            finally
            {
                CloseConnection();
                cmd.Dispose();
                cmd = null;
            }
        }

        private XmlReader ExecuteXmlReader(ref SqlCommand cmd)
        {
            try
            {
                return cmd.ExecuteXmlReader();
            }
            finally
            {
                CloseConnection();
                cmd.Dispose();
                cmd = null;
            }
        }

        private DataTable ExecuteDataTable(ref SqlDataAdapter adptr)
        {
            DataTable tbl = new DataTable();

            try
            {
                adptr.Fill(tbl);
                return tbl;
            }
            finally
            {
                CloseConnection();
                adptr.Dispose();
                adptr = null;
                tbl.Dispose();
                tbl = null;
            }
        }

        private DataSet ExecuteDataSet(ref SqlDataAdapter adptr)
        {
            DataSet ds = new DataSet();

            try
            {
                adptr.Fill(ds);
                return ds;
            }
            finally
            {
                CloseConnection();
                adptr.Dispose();
                adptr = null;
                ds.Dispose();
                ds = null;
            }
        }

        #endregion

        #region " Public Properties "

        public bool IsTransaction
        {
            // Is a transaction active not
            get
            {
                if (_transaction == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        public static HttpServerUtility HttpServer
        {
            get { return _httpServer; }
            set
            {
                if (_httpServer == null)
                {
                    _httpServer = value;
                }
            }
        }

        public static string ApplicationName
        {
            get { return _applicationName; }
            set
            {
                if (_applicationName == null)
                {
                    _applicationName = value;
                }
            }
        }

        public static bool ApplicationDebug
        {
            get { return _applicationDebug; }
            set { _applicationDebug = value; }
        }

        public static string LogFolder
        {
            get { return _logFolder; }
            set
            {
                if (_logFolder == null)
                {
                    _logFolder = value;
                    _logFolder = _logFolder + (_logFolder.EndsWith("/") ? "" : "/");
                    _logFolderAbsolute = HttpServer.MapPath(_logFolder);
                }
            }
        }

        public static string LogFolderAbsolute
        {
            get { return _logFolderAbsolute; }
        }

        public static string TempFolder
        {
            get { return _tempFolder; }
            set
            {
                if (_tempFolder == null)
                {
                    _tempFolder = value;
                    _tempFolder = _tempFolder + (_tempFolder.EndsWith("/") ? "" : "/");
                    _tempFolderAbsolute = HttpServer.MapPath(_tempFolder);
                }
            }
        }

        public static string TempFolderAbsolute
        {
            get { return _tempFolderAbsolute; }
        }

        public static string DBServerName
        {
            get { return _dbServerName; }
            set
            {
                if (_dbServerName == null)
                {
                    _dbServerName = value;
                }
            }
        }

        public static string DBName
        {
            get { return _dbName; }
            set
            {
                if (_dbName == null)
                {
                    _dbName = value;
                }
            }
        }

        public static string DBUser
        {
            get { return _dbUser; }
            set
            {
                if (_dbUser == null)
                {
                    _dbUser = value;
                }
            }
        }

        public static string DBPassword
        {
            get { return _dbPassword; }
            set
            {
                if (_dbPassword == null)
                {
                    _dbPassword = value;
                }
            }
        }

        public static string ConnectionString
        {
            //Return "Server=" & _dbServerName & ";Initial Catalog=" & _dbName & ";UID=" & _dbUser & ";Pwd= " & _dbPassword & ";Connection Timeout= 60;Integrated Security=True"
            get { return "Server=" + _dbServerName + ";Initial Catalog=" + _dbName + ";UID=" + _dbUser + ";Pwd= " + _dbPassword + ";Integrated Security=FALSE"; }
        }

        #endregion

        #region " IDisposable Implementation "

        public void Dispose()
        {
           if (_disposed)
            {
                return;
            }

            try
            {
                // Rollback current transaction
                if (this.IsTransaction)
                {
                    _transaction.Rollback();
                }
                _connection.Close();

                // Error while rolling back
            }
            catch (Exception ex)
            {
                _connection.Close();

            }
            finally
            {
                if ((_transaction != null))
                {
                    _transaction.Dispose();
                    _transaction = null;
                }

                if ((_connection != null))
                {
                    _connection.Dispose();
                    _connection = null;
                }

                _disposed = true;
                GC.SuppressFinalize(this);
            }
        }

        ~clsSQLHelper()
        {
            this.Dispose();
        }

        #endregion

        #region " Public Methods "

        public int ExecuteNonQuery(string SQLCommand, CommandType SQLType)
        {
            SqlCommand cmdObj = GetNewCommand(SQLCommand, SQLType);
            return ExecuteNonQuery(ref cmdObj);
        }

       public int ExecuteNonQuery(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteNonQuery(ref GetNewCommand(SQLProcedureName, SQLParameters));
            SqlCommand cmdObj = GetNewCommand(SQLProcedureName, ref SQLParameters);
            return ExecuteNonQuery(ref cmdObj);
        }

        public SqlDataReader ExecuteReader(string SQLCommand, CommandType SQLType)
        {
            //return ExecuteReader(GetNewCommand(SQLCommand, SQLType));
            SqlCommand cmdObj = GetNewCommand(SQLCommand, SQLType);
            return ExecuteReader(ref cmdObj);
        }

        public SqlDataReader ExecuteReader(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteReader(GetNewCommand(SQLProcedureName, SQLParameters));
            SqlCommand cmdObj = GetNewCommand(SQLProcedureName, ref SQLParameters);
            return ExecuteReader(ref cmdObj);
        }

        public object ExecuteScalar(string SQLCommand, CommandType SQLType)
        {
            //return ExecuteScalar(GetNewCommand(SQLCommand, SQLType));
            SqlCommand cmdObj = GetNewCommand(SQLCommand, SQLType);
            return ExecuteScalar(ref cmdObj);
        }

        public object ExecuteScalar(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteScalar(GetNewCommand(SQLProcedureName, SQLParameters));
            SqlCommand cmdObj = GetNewCommand(SQLProcedureName, ref SQLParameters);
            return ExecuteScalar(ref cmdObj);
        }

        public XmlReader ExecuteXmlReader(string SQLCommand, CommandType SQLType)
        {
            //return ExecuteXmlReader(GetNewCommand(SQLCommand, SQLType));
            SqlCommand cmdObj = GetNewCommand(SQLCommand, SQLType);
            return ExecuteXmlReader(ref cmdObj);
        }

        public XmlReader ExecuteXmlReader(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteXmlReader(GetNewCommand(SQLProcedureName, SQLParameters));
            SqlCommand cmdObj = GetNewCommand(SQLProcedureName, ref SQLParameters);
            return ExecuteXmlReader(ref cmdObj);
        }

        public DataTable ExecuteDataTable(string SQLCommand, CommandType SQLType)
        {
            //return ExecuteDataTable(new SqlDataAdapter(GetNewCommand(SQLCommand, SQLType)));
            SqlDataAdapter cmdObj = new SqlDataAdapter(GetNewCommand(SQLCommand, SQLType));
            return ExecuteDataTable(ref cmdObj);
        }

        public DataTable ExecuteDataTable(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteDataTable(new SqlDataAdapter(GetNewCommand(SQLProcedureName, SQLParameters)));
            SqlDataAdapter cmdObj = new SqlDataAdapter(GetNewCommand(SQLProcedureName, ref SQLParameters));
            return ExecuteDataTable(ref cmdObj);
        }

        public DataSet ExecuteDataSet(string SQLCommand, CommandType SQLType)
        {
            //return ExecuteDataSet(new SqlDataAdapter(GetNewCommand(SQLCommand, SQLType)));
            SqlDataAdapter cmdObj = new SqlDataAdapter(GetNewCommand(SQLCommand, SQLType));
            return ExecuteDataSet(ref cmdObj);
        }

        public DataSet ExecuteDataSet(string SQLProcedureName, ref SqlParameter[] SQLParameters)
        {
            //return ExecuteDataSet(new SqlDataAdapter(GetNewCommand(SQLProcedureName, SQLParameters)));
            SqlDataAdapter cmdObj = new SqlDataAdapter(GetNewCommand(SQLProcedureName, ref SQLParameters));
            return ExecuteDataSet(ref cmdObj);
        }

        // Refreshes all the resources and prepares SQLHelper for another execution
        public void Refresh(string ConnectionString)
        {
            _disposed = false;

            try
            {
                // Rollback current transaction
                if (this.IsTransaction)
                {
                    _transaction.Rollback();
                }
                _connection.Close();

                // Error while rolling back
            }
            catch (Exception ex)
            {
                _connection.Close();

            }
            finally
            {
                if ((_transaction != null))
                {
                    _transaction.Dispose();
                    _transaction = null;
                }

                if ((_connection != null))
                {
                    _connection.Dispose();
                    _connection = null;
                }

                _connection = new SqlConnection(ConnectionString);
                // Get a new connection
            }
        }

        public bool BeginTransaction()
        {
            // If transaction already exists, nothing happens else a transaction is created
            if (!this.IsTransaction)
            {
                OpenConnection();
                _transaction = _connection.BeginTransaction();
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool CommitTransaction()
        {
            // Commit the transaction if it exists else nothing happens
            try
            {
                if (this.IsTransaction)
                {
                    _transaction.Commit();
                    return true;
                }
                else
                {
                    return false;
                }

            }
            finally
            {
                if ((_transaction != null))
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                CloseConnection();
            }
        }

        public bool RollBackTransaction()
        {
            // Rollback transaction is it exists else nothing happens
            try
            {
                if (this.IsTransaction)
                {
                    _transaction.Rollback();
                    return true;
                }
                else
                {
                    return false;
                }

            }
            finally
            {
                if ((_transaction != null))
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                CloseConnection();
            }
        }

        #endregion
    }
}
2- DataFactory.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace NGOAutomateServices.Classes
{
    public class DataFactory:IDisposable
    {
        public enum cmdType
        {
            tableType,
            procType
        }

        #region "General variables"
        private SqlConnection _sqlconnection = null;
        private SqlCommand _sqlcmd;
        #endregion
        private string _constring;

        #region "Property variables"
        private string _retSingleValue;
        private SqlDataReader _retDRValue;
        #endregion
        private DataTable _retDTValue;

        #region "Function"
        private bool GetSQLConnection()
        {
            try
            {
                if (_sqlconnection == null)
                {

                    _constring = ConfigurationManager.AppSettings.Get("NGOConnectionString");
                    _sqlconnection = new SqlConnection(_constring);
                    _sqlconnection.Open();
                }
            }
            catch (Exception ex)
            {
                throw ex;
                return false;
            }
            return true;
        }
        private bool GetSQLConnectionProfileData()
        {
            try
            {
                if (_sqlconnection == null)
                {

                    _constring = ConfigurationManager.AppSettings.Get("ngoConnectionString");
                    _sqlconnection = new SqlConnection(_constring);
                    _sqlconnection.Open();
                }
            }
            catch (Exception ex)
            {
                throw ex;
                return false;
            }
            return true;
        }
        #endregion

        #region "Subroutine"
        public string GetSingleOuput(string query)
        {
            try
            {
                if (GetSQLConnection())
                {
                    _sqlcmd = new SqlCommand(query, _sqlconnection);
                    _retSingleValue = _sqlcmd.ExecuteScalar().ToString();
                    return _retSingleValue;
                }
                else
                {
                    return "";
                }

           }
            catch (Exception ex)
            {
                throw ex;
                return "";
            }
        }

        public void GetDataReaderOuput(string query)
        {
            try
            {
                if (GetSQLConnection())
                {
                    _sqlcmd = new SqlCommand(query, _sqlconnection);
                    _retDRValue = _sqlcmd.ExecuteReader();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataSet GetDataSet(string query, string tblName, cmdType ttype)
        {
            DataSet ds = null;
            SqlDataAdapter da = null;
            try
            {
                if (GetSQLConnection())
                {
                    _sqlcmd.CommandText = query;
                    _sqlcmd.Connection = _sqlconnection;
                    if (ttype == cmdType.procType)
                    {
                        _sqlcmd.CommandType = CommandType.StoredProcedure;
                    }
                    else
                    {
                        _sqlcmd.CommandType = CommandType.Text;
                    }
                    da = new SqlDataAdapter(_sqlcmd);
                    ds = new DataSet(tblName);
                    da.Fill(ds);
                }
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds.Dispose();
                da.Dispose();
            }
        }

        public void AddParameterSP(string key, string value)
        {
            _sqlcmd.Parameters.AddWithValue(key, value);
        }

        public void AddParameterImage(string key, byte[] img)
        {
            _sqlcmd.Parameters.AddWithValue(key, img);
        }

        public DataTable GetDataTable(string query, string tblName, cmdType ttype)
        {
            try
            {
                return GetDataSet(query, tblName, ttype).Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ExecuteSQL(string query, cmdType ttype)
        {
            if (GetSQLConnection())
            {
                _sqlcmd.CommandText = query;
                if (ttype == cmdType.procType)
                {
                    _sqlcmd.CommandType = CommandType.StoredProcedure;
                }
                else
                {
                    _sqlcmd.CommandType = CommandType.Text;
                }
                _sqlcmd.Connection = _sqlconnection;

                _sqlcmd.ExecuteNonQuery();
            }
        }

        //public string[] GetDisplayMenu()
        //{
        //    List<string> disp = new List<string>();
        //    if (GetSQLConnection())
        //    {
        //        using (SqlCommand cmd = new SqlCommand())
        //        {
        //            cmd.CommandText = "select DISTINCT disp_name, id FROM mst_disp_category where status ='A'";
        //            cmd.Connection = _sqlconnection;
        //            using (SqlDataReader sdr = cmd.ExecuteReader())
        //            {
        //                while (sdr.Read())
        //                {
        //                    disp.Add(string.Format("{0}:{1}", sdr("disp_name"), sdr("ID")));
        //                }
        //            }
        //        }
        //    }
        //    return disp.ToArray();
        //}

        //public string GetJsonByDataSet(string query, string tblName, cmdType ttype)
        //{
        //    return GetJson(GetDataTable(query, tblName, ttype));
        //}

        //private string GetJson(DataTable dt)
        //{
        //    System.Web.Script.Serialization.JavaScriptSerializer Jserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        //    List<Dictionary<string, object>> rowsList = new List<Dictionary<string, object>>();
        //    Dictionary<string, object> row = default(Dictionary<string, object>);
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        row = new Dictionary<string, object>();
        //        foreach (DataColumn col in dt.Columns)
        //        {
        //            row.Add(col.ColumnName, dr(col));
        //        }
        //        rowsList.Add(row);
        //    }
        //    return Jserializer.Serialize(rowsList);
        //}

        #endregion

        #region "IDisposable Support"
        // To detect redundant calls
        private bool disposedValue;

        // IDisposable
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    _sqlcmd.Dispose();
                    _sqlconnection.Close();
                    _sqlconnection.Dispose();
                }
                // TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
                // TODO: set large fields to null.
            }
            this.disposedValue = true;
        }

        // TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
        //Protected Overrides Sub Finalize()
        //    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        //    Dispose(False)
        //    MyBase.Finalize()
        //End Sub

        // This code added by Visual Basic to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        public DataFactory()
        {
            _sqlcmd = new SqlCommand();
        }
    }
}

3- GetHeaderParameter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Web;
using System.Web;

namespace NGOAutomateServices.Classes
{
    public class GetHeaderParameter
    {
        string userID = string.Empty;
        string oprtype = string.Empty;
        public string GetReturnuseridoprtype()
        {

            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection headers = request.Headers;
            string strParam = string.Empty;
            for (int i = 0; i < headers.Count;i++)
            {
                if (headers["userid"] != null)
                {
                    userID = headers["userid"];
                }

                if (headers["oprtype"] != null)
                {
                    oprtype = headers["oprtype"];
                }
                break;
            }
            strParam = userID + "|" + oprtype;
            return strParam;
       }
    }
}

4- ITISGItemEntity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NGOAutomateServices.Classes
{
    public class ITISGItemEntity
    {
        public class ResultData
        {
            public string Success { getset; }
            public string Data { getset; }
        }
    }
}

5- JSonHelper.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

namespace NGOAutomateServices.Classes
{
    public class JSonHelper
    {

        public string ConvertObjectToJSon<T>(T obj)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, obj);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        public T ConvertJSonToObject<T>(string jsonString)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)serializer.ReadObject(ms);
            return obj;
        }
    }
}



NGOITISGServices.svc :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using static NGOAutomateServices.Classes.ITISGItemEntity;
using System.Data.SqlClient;
using System.Data;
using NGOAutomateServices.Classes;
using Newtonsoft.Json;
using System.Configuration;

namespace NGOAutomateServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "NGOITISGServices" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select NGOITISGServices.svc or NGOITISGServices.svc.cs at the Solution Explorer and start debugging.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class NGOITISGServices : INGOITISGServices
    {
        // Using PostMan
        //http://s07ssharv008lvs:32142/NGOAutoITISGServices/NGOITISGServices.svc/GetUserProfileData  //select in Header Content type :application/json && Method Post &&&& Go --Body -row ({"userid":"NGO\\ramvinay","oprtype":"3"})




        #region Variable declartion
        clsSQLHelper objSQLHelper;
        #endregion

        #region Demo Method to create Service
        //public string AddPayee(string Name, string City)
        //{
        //    return "write database related update logic here" + Name + "" + City + "";
        //}
        //public string PayBill(string PayId)
        //{
        //    GetHeaderParameter objGetHeaderParameter = new GetHeaderParameter();
        //    string str=objGetHeaderParameter.GetReturnuseridoprtype();
        //    return "Transaction having PayId by Ram " + str + " is successful";
        //    //write database related data retrival logic here.   
        //}
        //public string RemovePayee(string Id)
        //{
        //    return "write database related delete logic here  "+ Id +" ";
        //}

        //public string UpdateBillPayment(string PayId, string TransId)
        //{
        //    return "write database related update logic here" + PayId + ""+ TransId + "";
        //}
        #endregion


        #region Get  User wise detail of Employee
        private clsSQLHelper GetDBConnectionMONE_LOG()
        {
            if (objSQLHelper == null)
            {
                objSQLHelper = new clsSQLHelper(ConfigurationManager.AppSettings.Get("NGOConnectionString"));
            }
            return objSQLHelper;
        }
        public ResultData GetUserProfileData(string userid, int oprtype)
        {
            ResultData ObjResultData = new ResultData();
            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@p_userid", userid),
                    new SqlParameter("@p_oprtype", oprtype)
                };

                DataTable dtData = new DataTable();
                GetDBConnectionMONE_LOG();
                dtData = objSQLHelper.ExecuteDataTable("[dbo].[GetUserProfileData]"ref parameters);
                ObjResultData.Data = JsonConvert.SerializeObject(dtData);
                ObjResultData.Success = "Y";
                return ObjResultData;
            }
            catch (Exception ex)
            {
                ObjResultData.Success = "N";
                ObjResultData.Data = ex.Message;
            }
            return ObjResultData;
        }

        public ResultData GetUserProfileData1()
        {
            GetHeaderParameter objGetHeaderParameter = new GetHeaderParameter();
            string struseridoprtype = objGetHeaderParameter.GetReturnuseridoprtype();
            ResultData ObjResultData = new ResultData();
            if (struseridoprtype != "")
            {
                string userid = String.Empty;
                string[] useridoprtype = struseridoprtype.ToString().Split('|');
                if (useridoprtype[0] != "" && useridoprtype[1] != "")
                {
                    userid = useridoprtype[0];
                    int oprtype = Convert.ToInt32(useridoprtype[1]);
                    try
                    {
                        SqlParameter[] parameters =
                        {
                    new SqlParameter("@p_userid", userid),
                    new SqlParameter("@p_oprtype", oprtype)
                };

                        DataTable dtData = new DataTable();
                        GetDBConnectionMONE_LOG();
                        dtData = objSQLHelper.ExecuteDataTable("[dbo].[GetUserProfileData]"ref parameters);
                        ObjResultData.Data = JsonConvert.SerializeObject(dtData);
                        ObjResultData.Success = "Y";
                        return ObjResultData;
                    }
                    catch (Exception ex)
                    {
                        ObjResultData.Success = "N";
                        ObjResultData.Data = ex.Message;
                    }
                }
            }
            return ObjResultData;
        }
        #endregion

    }
}

INGOITISGServices.svc:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using static NGOAutomateServices.Classes.ITISGItemEntity;

namespace NGOAutomateServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "INGOITISGServices" in both code and config file together.
    [ServiceContract]
    public interface INGOITISGServices
    {
        #region Demo Method to create Service
        ////To Insert or POST Records 
        //[OperationContract]
        //[WebInvoke(Method = "POST", UriTemplate = "/AddPayee/{Name}/{City}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        //string AddPayee(string Name, string City);


        //[OperationContract]
        //[WebInvoke(Method = "POST", UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        //string PayBill(string PayId);

        ////To Update records 
        //[OperationContract]
        //[WebInvoke(Method = "PUT",UriTemplate = "/UpdateBillPayment/{PayId}/{TransId}",BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        //string UpdateBillPayment(string PayId, string TransId);


        ////To delete records 
        //[OperationContract]
        //[WebInvoke(Method = "DELETE",UriTemplate = "/RemovePayee/{Id}",BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        //string RemovePayee(string Id);

        #endregion

        #region Get  User wise detail of Employee
        // Start This OperationContract Passing parameter Value in Header Only
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetUserProfileData1", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)]
        ResultData GetUserProfileData1();
        // End  This  OperationContract Passing parameter Value in Header Only

        // Start This  OperationContract Passing parameter Value in select in Header Content type :application/json && Method Post &&&& Go -->Body ->row ({"userid":"NGO\\ramvinay","oprtype":"3"})) Only
        [OperationContract]
        [WebInvoke(UriTemplate = "/GetUserProfileData", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)]
        ResultData GetUserProfileData(string userid, int oprtype);

        // End This OperationContract Passing parameter Value in select in Header Content type :application/json && Method Post &&&& Go -->Body ->row ({"userid":"NGO\\ramvinay","oprtype":"3"})) Only
        #endregion

    }
}


No comments:

Post a Comment