Sunday, 18 December 2016

Enable Cors in webapi

No comments
Web.Config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>


WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // ...
    }
}

Attributes

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]


For Globally

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }

}

Global.asax.cs

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}
read more

Friday, 2 December 2016

Sql Important Queries

No comments
Rename Database 

use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE  
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER


Delete all Table

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' Drop table [' + TABLE_SCHEMA + '].['+ TABLE_NAME + ']'
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'


Exec Sp_executesql @sql


Basic Cursur

declare @procName varchar(500)
declare cur cursor 

for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
    exec('drop procedure [' + @procName + ']')
    fetch next from cur into @procName
end
close cur
deallocate cur




read more

Monday, 28 November 2016

Setting PayPal in ionic project

No comments
Install PayPal cordova plugin from

https://github.com/paypal/PayPal-Cordova-Plugin

create service



app.factory('PaypalService', ['$q', '$ionicPlatform', 'shopSettings', '$filter', '$timeout','RequestData', function ($q, $ionicPlatform, shopSettings, $filter, $timeout,RequestData) {
    debugger
    var init_defer;
    /**
     * Service object
     * @type object
     */
    var service = {
        initPaymentUI: initPaymentUI,
        createPayment: createPayment,
        configuration: configuration,
        onPayPalMobileInit: onPayPalMobileInit,
        makePayment: makePayment
    };
    /**
     * @ngdoc method
     * @name initPaymentUI
     * @methodOf app.PaypalService
     * @description
     * Inits the payapl ui with certain envs.
     *
     *
     * @returns {object} Promise paypal ui init done
     */
    function initPaymentUI() {
        init_defer = $q.defer();
        $ionicPlatform.ready().then(function () {
            debugger
                var promisePost = RequestData.GetPaypalCredential();
                promisePost.then(function (data) {
                debugger
                    var clientIDs = {
                        "PayPalEnvironmentSandbox": data.data.PayPalEnvironmentSandbox,
                        "PayPalEnvironmentProduction": data.data.PayPalEnvironmentProduction
                    };
                    PayPalMobile.init(clientIDs, indexApp.onPayPalMobileInit());
                });        
        });
        return init_defer.promise;
    }
    /**
     * @ngdoc method
     * @name createPayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Creates a paypal payment object
     *
     *
     * @returns {object} PayPalPaymentObject
     */
    function createPayment(total, name) {              
        // "Sale  == >  immediate payment
        // "Auth" for payment authorization only, to be captured separately at a later time.
        // "Order" for taking an order, with authorization and capture to be done separately at a later time.
        var payment = new PayPalPayment("" + total, "EUR", "" + name, "Sale");
        return payment;
    }
    /**
     * @ngdoc method
     * @name configuration
     * @methodOf app.PaypalService
     * @description
     * Helper to create a paypal configuration object
     *
     *
     * @returns {object} PayPal configuration
     */
    function configuration() {
        // for more options see `paypal-mobile-js-helper.js`
        var config = new PayPalConfiguration({merchantName: shopSettings.payPalShopName, merchantPrivacyPolicyURL: shopSettings.payPalMerchantPrivacyPolicyURL, merchantUserAgreementURL: shopSettings.payPalMerchantUserAgreementURL});
        return config;
    }
    function onPayPalMobileInit() {
        $ionicPlatform.ready().then(function () {
            // must be called
            // use PayPalEnvironmentNoNetwork mode to get look and feel of the flow
            PayPalMobile.prepareToRender(shopSettings.payPalEnv, configuration(), function () {
                $timeout(function () {
                    init_defer.resolve();
                });

            });
        });
    }
    /**
     * @ngdoc method
     * @name makePayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Performs a paypal single payment
     *
     *
     * @returns {object} Promise gets resolved on successful payment, rejected on error
     */
    function makePayment(total, name) {
        var defer = $q.defer();
        total = $filter('number')(total, 2);
        $ionicPlatform.ready().then(function () {
            PayPalMobile.renderSinglePaymentUI(createPayment(total, name), function (result) {
                $timeout(function () {
                    defer.resolve(result);
                });
            }, function (error) {
                $timeout(function () {
                    defer.reject(error);
                });
            });
        });
        return defer.promise;
    }
    return service;
}]);  
//To use this service
//PaypalService.initPaymentUI().then(function () {
//    PaypalService.makePayment($scope.total(), "Total").then(...)
//});
   
// shop settings
// include appConstant into your app.js
app.constant('shopSettings',{        
    payPalEnv: 'PayPalEnvironmentSandbox',   // for testing  production for production
    payPalShopName : 'GoHealthNow',
    payPalMerchantPrivacyPolicyURL : 'https://mytestshop.com/policy',
    payPalMerchantUserAgreementURL : 'https://mytestshop.com/agreement'  

});

Pay Button CLick

app.controller('PaymentCtrl', ['PaypalService',

    function (PaypalService) {
 $scope.PayPaymnt = function () {        
                PaypalService.initPaymentUI().then(function () {
                    PaypalService.makePayment(100, "Total").then(function () {                  
                        $state.go('app.orderComplete', { completeId: 1 });
                    });
                });
            }      

        }
});
read more

Sunday, 20 November 2016

Environment setting for cordova

No comments
USER VARIABLE
--------------------------------------------------------------------------------------------------------------


ANDROID

VariableName - ANDROID_HOME
VariableValue - C:\Program Files (x86)\Android\android-sdk


NPM/CORDOVA

C:\Users\me\AppData\Roaming\npm\node_modules\cordova\bin

C:\Users\vikas\AppData\Roaming\npm


SYSTEM VARIABLE
-----------------------------------------------------------------------------------------------------------------
VN - ADT_HOME
VV - C:\Program Files (x86)\Android\android-sdk


VN - ANDROID_NDK_PATH
VV - C:\Program Files\Android\ndk\android-ndk-r11c

VN - ANT_HOME
VV - C:\apache-ant-1.9.3

VN - GIT_HOME
VV - C:\Program Files (x86)\Git

VN - JAVA_HOME
VV - C:\Program Files (x86)\Java\jdk1.7.0_55
read more

Friday, 18 November 2016

Payment with Sudopay for Authorize.net

No comments
 public class SudopayResponse
    {
        public int id { get; set; }
        public DateTime created { get; set; }
        public DateTime modified { get; set; }
        public string status { get; set; }
        public string paykey { get; set; }        
        public SudopayResponseError error { get; set; }
    }


    public class SudopayResponseErrorArray
    {
        public SudopayResponseError[] SudopayResponseError { get; set; }
    }
    public class SudopayResponseError
    {
        public string code { get; set; }
        public string message { get; set; }
    }



[HttpPost]
        public HttpResponseMessage PayForRideWithSudopay()
        {
            string requestBody = string.Empty;
            requestBody = HttpMessage(requestBody);
            var callForRideRequest = JsonConvert.DeserializeObject<CallForRideRel>(requestBody);
            if (callForRideRequest.CallForRideId == null)
            {
                return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "There was problem in processing your payment");
            }

            try
            {
                var callForRideRepository = uow.Repository<CallForRideRepository>();
                var callForRideData = callForRideRepository.GetRideById((int)callForRideRequest.CallForRideId);

                var userRideRepository = uow.Repository<UserRideRepository>();
                var userRideData = userRideRepository.GetRideByCallForRide((int)callForRideRequest.CallForRideId);

                var userRepository = uow.Repository<UserRepository>();
                var userData = userRepository.GetUsersById((int)userRideData.UserId);

                var userCreditCardRepository = uow.Repository<UserCreditCardRepository>();
                var creditCardData = userCreditCardRepository.GetUserCreditCard(((int)userRideData.UserId)).Where(x => x.IsDefault == true).FirstOrDefault();

                var countryRepository = uow.Repository<CountryRepository>();
                var countryData = countryRepository.GetContryById((int)userData.CountryId);

                if (userRideData != null && countryData != null)
                {
                    userRideData.IsAmountPaid = true;

                    UnitOfWork uow = new UnitOfWork();
                    var appConfigCodeRepository = uow.Repository<AppConfigRepository>();
                    var appConfigCode = appConfigCodeRepository.GetByGroupName("payment");

                    System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
                    string websiteId = appConfigCode.FirstOrDefault(x => x.Name == "Website").Value;

                    #region Sudopay Capture
                    Inputs = new System.Collections.Specialized.NameValueCollection();
                    Inputs.Add("website_id", websiteId);
                    Inputs.Add("currency_code", appConfigCode.FirstOrDefault(x => x.Name == "CurrencyCode").Value);
                    Inputs.Add("amount", callForRideRequest.RideAmount.ToString());
                    Inputs.Add("item_name", "Pay For Ride");
                    Inputs.Add("item_description", "Ride From '" + callForRideData.Source + "' to '" + callForRideData.ActualDestination + "'");
                    Inputs.Add("buyer_ip", Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString());
                    Inputs.Add("buyer_address", userData.Address);
                    Inputs.Add("buyer_city", userData.City);
                    Inputs.Add("buyer_country", countryData.CountryCode.ToString());
                    Inputs.Add("buyer_email", userData.Email);
                    Inputs.Add("buyer_phone", userData.Mobile);
                    Inputs.Add("buyer_state", userData.State);
                    Inputs.Add("buyer_zip_code", userData.ZipCode);

                    Inputs.Add("credit_card_number", creditCardData.LastFourDigit);
                    Inputs.Add("credit_card_expire", creditCardData.ExpMonth + "/" + creditCardData.ExpYear);
                    Inputs.Add("credit_card_name_on_card", creditCardData.NameOnCard);
                    Inputs.Add("credit_card_code", creditCardData.CVV);
               
                    Inputs.Add("success_url", appConfigCode.FirstOrDefault(x => x.Name == "success_url").Value);
                    Inputs.Add("cancel_url", appConfigCode.FirstOrDefault(x => x.Name == "success_url").Value);

                    WebClient client = new WebClient();
                    client.Headers.Add("Authorization", string.Concat("Basic ", appConfigCode.FirstOrDefault(x => x.Name == "SudopayAuth").Value));
                    byte[] response = client.UploadValues("http://sandbox.sudopay.com/api/v1/merchants/11337/gateways/2/payments/capture.json", Inputs);
                    string result = System.Text.Encoding.UTF8.GetString(response);
                    result = result.Replace("[", "'");
                    result = result.Replace("]", "'");
                    var sudopayResponseData = JsonConvert.DeserializeObject<SudopayResponse>(result);

                    #endregion
                    if (sudopayResponseData.status == "Error")
                    {
                        return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, sudopayResponseData.error.message);
                    }
                    userRideData.TransactionId = sudopayResponseData.paykey;
                    userRideRepository.UpdateUserRide();
                    return this.Request.CreateResponse(HttpStatusCode.OK, "Success");
                }
                else
                {
                    return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "Please check if you have valid information i.e country,state,zipcode");
                }
            }
            catch (Exception ex)
            {

                logger.Error(ex.Message, ex.Message);
                return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "Something went wrong");
            }
        }
read more

Send message with CallFire

No comments
public static string SendText(string number, string message)
        {
            UnitOfWork uow = new UnitOfWork();
            var appConfigCodeRepository = uow.Repository<AppConfigRepository>();
            var appConfigCode = "CallFireAuth";

            var webAddr = "https://api.callfire.com/v2/texts";
            var webrequest = (HttpWebRequest)WebRequest.Create(webAddr);
            webrequest.Method = "POST";
            webrequest.ContentType = "application/json";
            webrequest.Headers.Add("Authorization", String.Concat("Basic ", appConfigCode.Value));

            using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
            {                              
                string json = "[{\"message\":\"" + message + "\",\"phoneNumber\":\"" + number + "\"}]";
                streamWriter.Write(json);
            }
            StreamReader reader = null;
            string stripeResponse;
            try
            {
                HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
                Stream responseStream = webresponse.GetResponseStream();
                reader = new StreamReader(responseStream);
                return stripeResponse = reader.ReadToEnd();
            }
            catch (WebException exception)
            {
                using (WebResponse response = exception.Response)
                {
                    using (Stream data = response.GetResponseStream())
                    using (reader = new StreamReader(data))
                    {
                        return stripeResponse = reader.ReadToEnd();
                    }
                }
            }
        }

 public class CallFireResponse
    {

        public int httpStatusCode { get; set; }
        public string internalCode { get; set; }
        public string message { get; set; }

    }
read more

SignalR example - mvc

No comments
ContachHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Repository.Pattern;
using CarribeaneTaxi.Entity;
using System.IO;

namespace signalRTest.Hubs
{
    public class ContactHub : Hub
    {
        UnitOfWork uow = new UnitOfWork();  
        public void addRequest(Guid GUID, int Id)
        {
            var userRepository = uow.Repository<UserRepository>();
            var userData = userRepository.GetUsersByGUID(GUID);

            var repository = uow.Repository<Repository>();
            var data = repository .GetAll(Id);

            Clients.All.addRequest(userData.UserId, userData.Name, DateTime.Now, GUID);
        }

        public static void addRequest1(string name, string message)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ContactHub>();
            hubContext.Clients.All.broadcastMessage(name, message);
        }

    }

}


Startup.cs

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
[assembly: OwinStartupAttribute(typeof(signalRTest.Startup))]
namespace signalRTest
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR();
            });      
        }
    }

}


JQUERY

<script src="Scripts/jquery.signalR-2.2.0.js"></script>
 <script src="http://localhost:4562/signalr/hubs"></script>

Common.SignalRURL: function () {
            return 'http://localhost/signalr';
        },

<script type="text/javascript">
        var contactNotifyUsers = undefined;
        $.connection.hub.url = CarribeanCommon.SignalRURL();
        contactNotifyUsers = $.connection.contactHub;
    </script>


Client where you get response 


   //set signalr real time data fetch        
        $.connection.hub.url =Common.SignalRURL();
        contactNotifyUsers = $.connection.contactHub;
        contactNotifyUsers.client.addRequest = function (userId, name, date, GUID) {
            setTimeout(function () {
                if (localStorage.getItem('GUID').toUpperCase() == GUID.toUpperCase()) {
                 
                }
            }, 1000);
        }
        $.connection.hub.start();

//Or

       $.connection.hub.url = Common.SignalRURL();
        $.connection.contactHub.client.broadcastMessage = function (id, name) {
            if (id == userId) {
                $scope.callerName = name;
                $scope.ShoWpop();
                $scope.$apply();
            }
        };
        $.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(function () {
            setTimeout(function () {
                contactNotifyUsers.server.addRequest1('displayname', 'message');
            }, 2000)
        });




Request to server 


$.connection.hub.url = CarribeanCommon.SignalRURL();
                    contactNotifyUsers = $.connection.contactHub;
                    $.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(function () {
                        contactNotifyUsers.server.addRequest(localStorage.getItem('GUID'), Id);
                        if (window.location.hash == '#/userCurrentRide') {
                            $route.reload();
                        }
                    });
read more

Friday, 4 November 2016

T-SQL Query Example

No comments
declare @drugname int =null
declare @clientid  int=null
declare @mfgid int=NULL

DECLARE @Skip INT
DECLARE @Take INT    
DECLARE @SQL VARCHAR(MAX)


declare @q varchar(max)='SELECT * FROM (SELECT ROW_NUMBER() OVER
(ORDER BY drugid asc) rownumber,*,(select unitname from UnitDetails where UnitDetails.unitid= Drug.unitid) as unitname,
(select mfgname from Manufacture where Manufacture.mfgid= Drug.mfgid) as mfgname
from Drug
where drugid = coalesce('+case when @drugname is not null then cast(@drugname as varchar) else 'NULL'end+',drugid,'''')
AND
mfgid '+case when @mfgid > 0 then '=('+cast(@mfgid as varchar)+')' else ' is null or mfgid = mfgid' end+'
) A '

execute(@q)
select @q
read more

Saturday, 29 October 2016

Print with javascript

No comments
Javascript

function PrintLabel(jsonData) {  
    jsonData = JSON.parse(jsonData);
    var frame1 = document.createElement('iframe');
    frame1.name = "frame1";
    frame1.style.position = "absolute";
    frame1.style.top = "-1000000px";

    document.body.appendChild(frame1);

    var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
    frameDoc.document.open();
    frameDoc.document.write('<html><head><title> &nbsp;</title><link href="../Content/Default.css" rel="stylesheet" />');
    frameDoc.document.write('</head><body>');
    for (var i = 0; i < jsonData.length; i++) {
        frameDoc.document.write("<div id='dvClient'><label style='font-family:\"Arial\"' id='pName'>" + jsonData[i].ClientName + "</label><div>");
        //frameDoc.document.write('</br>');
        frameDoc.document.write("<label style='font-family:\"Arial\"'>" + "Dr. " + jsonData[i].ProviderName + "</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("<label style='font-family:\"Arial\"' id='patientPrint'>" + jsonData[i].PatientName + "  " + jsonData[i].PatientChart + "</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("<label style='font-family:\"Arial\"'>" + jsonData[i].DrugName + "  " + jsonData[i].ShortOutDate + "</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("<label style='font-family:\"Arial\"'>Qty: " + jsonData[i].outqty + " " + jsonData[i].UnitName + "  Lot: " + jsonData[i].lotno + " Exp: " + jsonData[i].ExpDate + "</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("<label style='font-family:\"Arial\"'>" + jsonData[i].sig + "</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("</br>");      
        frameDoc.document.write("<label style='font-family:\"Arial\"'>Caution:</label>");
        frameDoc.document.write('</br>');
        frameDoc.document.write("<div id='dvCaution'><label style='font-family:\"Arial\"'>Federal law prohibits </label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>transfer of this drug to any </label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>person other than patient </label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>for whom prescribed.</label></br><div>");
        frameDoc.document.write("<br/>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>Call your doctor for medical</label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>advice about drug side</label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>you may report drug side effects</label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>effects to the FDA at:</label></br>");
        frameDoc.document.write("<label style='font-family:\"Arial\"'>1-800-FDA-1088</label></br>");
        frameDoc.document.write("<br/>");
        frameDoc.document.write("<br/>");
    }
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        window.frames["frame1"].print();
        document.body.removeChild(frame1);
    }, 500);
    return false;
}

CSS

/* A4 Landscape*/
@page {
    size: auto;
    margin: 0;

}

#pName {
    zoom: 1.5;
}

#dvClient {
    text-align: center;
}
#dvPatient {
    width: 2.20in;
    height: 1.25in;    
    background: white;    
}

read more

CRUD with AJX in mvc

No comments
Controller

      //View
        public ActionResult InstructionWord()
        {
            InstructionWordRel instructionWordRel = new InstructionWordRel();
            BindInstructionWordGrid(instructionWordRel);
            return View(instructionWordRel);
        }

      //Bind
        public void BindInstructionWordGrid(InstructionWordRel instructionWordRel)
        {
            int _currentPage = 1;
            string insWord = string.Empty;
            int PageSize = 5;

            if (!int.TryParse(Request.QueryString["pg"], out _currentPage))
            {
                _currentPage = 1;
            }
            if (!string.IsNullOrEmpty(Request.QueryString["InsWord"]))
            {
                insWord = Request.QueryString["InsWord"];
            }
            instructionWordRel.CurrentPage = _currentPage;
            var instructionWordRelRepository = uom.Repository<InstructionWordRelRepository>();
            var result = instructionWordRelRepository.ExecWithStoreProcedure("spViewSIG @PageSize,@CurrentPage,@InsWord",
                new SqlParameter("PageSize", SqlDbType.Int) { Value = PageSize },
                new SqlParameter("CurrentPage", SqlDbType.Int) { Value = _currentPage },
                new SqlParameter("InsWord", SqlDbType.NVarChar, 100) { Value = insWord }
                ).ToList();

            instructionWordRel.TotalRecordCount = (instructionWordRelRepository.ExecWithStoreProcedure("spCountSIG @InsWord",
               new SqlParameter("InsWord", SqlDbType.NVarChar, 50) { Value = insWord }
               ).FirstOrDefault().TotalRecordCount);

            int pageCount = instructionWordRel.TotalRecordCount / PageSize;
            pageCount = instructionWordRel.TotalRecordCount % PageSize > 0 ? pageCount + 1 : pageCount;
            instructionWordRel.TotalPageCount = pageCount;
            instructionWordRel.lstInstructionWordRel = result;
        }

       //Update - Insert
        [HttpPost]
        public ActionResult InstructionWord(InstructionWordRel instructionWordRel)
        {
            if (string.IsNullOrEmpty(instructionWordRel.InsWord) || Convert.ToInt32(instructionWordRel.EnumInsWord) == 0)
            {
                ModelState.AddModelError("Error", "Please provide valid input");
                goto Exit;
            }

            var instructionnWordRepository = uom.Repository<InstructionWordsRepository>();
            if (instructionWordRel.InsWordID > 0)
            {
                var instructionnWordDetails = instructionnWordRepository.Get(x => x.InsWordID == instructionWordRel.InsWordID);
                instructionnWordDetails.InsWord = instructionWordRel.InsWord;
                instructionnWordDetails.InsType = Convert.ToInt32(instructionWordRel.EnumInsWord);
                instructionnWordRepository.Attach(instructionnWordDetails);
                ViewBag.message = "Updated";
            }
            else
            {
                InstructionWords instructionWords = new InstructionWords();
                instructionWords.InsType = Convert.ToInt32(instructionWordRel.EnumInsWord);
                instructionWords.InsWord = instructionWordRel.InsWord;
                instructionnWordRepository.Add(instructionWords);              
                ViewBag.message = "Added";              
            }
            ModelState.Clear();
            instructionWordRel = new InstructionWordRel();
            Exit:
            BindInstructionWordGrid(instructionWordRel);
            return View(instructionWordRel);
        }

        //Edit
        public ActionResult EditInstructionWord(InstructionWordRel instructionWordRel)
        {
            var instructionnWordRepository = uom.Repository<InstructionWordsRepository>();
            var instructionData = instructionnWordRepository.Get(x => x.InsWordID == instructionWordRel.InsWordID);
            instructionWordRel.InsWord = instructionData.InsWord;
            instructionWordRel.InsType = instructionData.InsType;
            //instructionWordRel.InsType = unitData.unitid;
            BindInstructionWordGrid(instructionWordRel);
            return Json(instructionWordRel, JsonRequestBehavior.AllowGet);
        }

        //Delete
        [HttpPost]
        public ActionResult DeleteInstructionWord(InstructionWordRel instructionWordRel)
        {
            var instructionnWordRepository = uom.Repository<InstructionWordsRepository>();
            var drugData = instructionnWordRepository.Get(x => x.InsWordID== instructionWordRel.InsWordID);
            instructionnWordRepository.Delete(drugData);
            return Json("Deleted");
        }

CSHTML

    <div class="main-content">
        <div class="panel mb25">
            <div class="panel-heading border">
                View SIG
            </div>
            <div class="panel-body">
                <div class="row no-margin">
                    <div class="col-lg-12">
                        <div class="box">
                            <div class="box-body no-padding">
                                <div class="row col-md-9">
                                    <div class="form-group">
                                        <label class="control-label col-sm-1">
                                            SIG:
                                        </label>
                                        <div class="col-sm-3">
                                            <input type="text" id="sigSearch" class="form-control" />
                                        </div>
                                        <button class="btn btn-primary" id="btnSearch" onclick="SearchData('search');return false;">Search</button>
                                        <button class="btn btn-primary" id="btnReset" onclick="SearchData('reset');return false;">Reset</button>
                                    </div>
                                </div>
                                <div class="row col-sm-12">
                                    <table class="table">
                                        <tr>
                                            <th class="textLeft">
                                                SIG
                                            </th>
                                            <th></th>
                                        </tr>
                                        @foreach (var item in @Model.lstInstructionWordRel)
                                        {
                                            <tr>
                                                <td>@item.InsWord</td>
                                                <th class="col-md-1">
                                                    <a href="javascript:void(0)" onclick="EditInstruction(@item.InsWordID)"><i class="fa fa-pencil fa-fw" aria-hidden="true"></i></a>
                                                    <a href="javascript:void(0)" onclick="DeleteInstruction(@item.InsWordID)"><i class="fa fa-trash fa-fw" aria-hidden="true"></i></a>
                                                </th>
                                            </tr>
                                        }
                                    </table>
                                </div>
                            </div>
                            <div class="box-footer">
                                <ul class="pagination pagination-sm no-margin pull-right">
                                    @if (Model.CurrentPage > 1)
                                    {
                                        <li>
                                            <a href="?pg=@(Model.CurrentPage > 1 ? (Model.CurrentPage - 1) : Model.CurrentPage)&InsWord=@(Request.QueryString["InsWord"] != null ? Request.QueryString["InsWord"] : "")">&laquo;</a>
                                        </li>
                                    }
                                    else
                                    {
                                        <li class="disabled">
                                            <a href="javascript:void(0);">&laquo;</a>
                                        </li>
                                    }
                                    @if (Model.TotalPageCount > 0)
                                    {
                                        for (int i = (Model.CurrentPage > 3 ? (Model.CurrentPage - 2) : 1); i < (Model.CurrentPage > 3 ? (Model.CurrentPage) + 3 : 6); i++)
                                        {
                                            if (Model.TotalPageCount >= i)
                                            {
                                                <li class="@(i == (Model.CurrentPage) ? "active" : "")">
                                                    <a class="@(i == (Model.CurrentPage) ? "selected" : "")" href="?pg=@i&InsWord=@(Request.QueryString["InsWord"] != null ? Request.QueryString["InsWord"] : "")">@(i)</a>
                                                </li>
                                            }
                                        }
                                    }
                                    @if (Model.CurrentPage < Model.TotalPageCount)
                                    {
                                        <li>
                                            <a href="?pg=@(Model.TotalPageCount == Model.CurrentPage ? (Model.TotalPageCount).ToString() : (Model.CurrentPage + 1).ToString())&InsWord=@(Request.QueryString["InsWord"] != null ? Request.QueryString["InsWord"] : "")">&raquo;</a>
                                        </li>
                                    }
                                    else
                                    {
                                        <li class="disabled"><a href="javascript:void(0);">&raquo;</a></li>
                                    }
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <input type="hidden" id="hdnInsWordID" />
        </div>
    </div>
    <div class="main-content" style="padding-top:5px !important">
        <div class="panel mb25">
            <div class="panel-heading border">
                Create SIG
            </div>
            <div class="panel-body">
                @Html.Partial("PartialView/_InstructionWord")
            </div>
        </div>
    </div>
    <div class="modal" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">Delete Confirmation</h4>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this InstructionWord?</p>
                </div>
                <div class="modal-footer">
                    <input id="hdAnAddressBookId" type="hidden" />
                    <button data-dismiss="modal" class="btn btn-default pull-left" type="button">Close</button>
                    <button class="btn btn-danger" type="button" onclick="ConfirmDeleteItem()">Delete</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
    </div>

    @section Scripts
    {
        <script type="text/javascript">
            $(document).ready(function () {
                //Show success message after data is inserted
                if ('@ViewBag.message' == "Added") {
                    toastr.success('Record added sucessfully', 'Success', { timeOut: 5000 });
                }
                else if ('@ViewBag.message' == "Updated") {
                    toastr.success('Record updated sucessfully', 'Success', { timeOut: 5000 });
                }
            });
            function EditInstruction(instructionId) {
                $.ajax({
                    type: "GET",
                    url: "@Url.Action("EditInstructionWord", "Master")",
                    data: { InsWordID: instructionId },
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (responseData) {                      
                        $("#EnumInsWord").val(responseData.InsType);
                        $("#InsWord").val(responseData.InsWord);
                        $("#InsWordID").val(responseData.InsWordID);

                    },
                    error: function (e) {
                    }
                });
            }

            function ConfirmDeleteItem() {
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("DeleteInstructionWord", "Master")?InsWordID=" + $('#hdnInsWordID').val(),
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (responseData) {
                        window.location.href = window.location.href;
                    },
                    error: function (e) {
                    }
                });
            }

            function DeleteInstruction(InsWordID) {
                $('#deleteModal').modal('toggle');
                $('#deleteModal').modal('show');
                $('#hdnInsWordID').val(InsWordID);
            }
        </script>

    }

Partial View CSHTML

<div class="panel-body">
    <div class="row no-margin">
        <div class="col-lg-12">
            @if (ViewContext.ViewData.ModelState.ContainsKey("Error"))
            {
                <div class="alert alert-danger alert-dismissible dvErrorListServer" style="width: 50%">
                    <button type="button" class="close " data-dismiss="alert" aria-hidden="true" style="margin-right:15px!important">×</button>
                    @Html.ValidationSummary(false)
                </div>
            }
            <div class="col-md-12">
                <div class="form-group no-margin">
                    <label class="col-sm-2 control-label">SIG Type</label>
                    <div class="col-sm-4">
                        @Html.EnumDropDownListFor(x => x.EnumInsWord, "Type", new { tabindex = "1", @class = "form-control" })
                    </div>
                </div>

                <div class="form-group no-margin">
                    <label class="col-sm-2 control-label">SIG Name</label>
                    <div class="col-sm-4">
                        @Html.TextBoxFor(x => x.InsWord, new { maxlength = "50", tabindex = "1", @class = "form-control" })
                    </div>
                </div>
                <div class="form-group no-margin">
                    <label class="col-sm-2 control-label">&nbsp;</label>
                    <div class="col-sm-4">
                        <button class="btn btn-primary mr10" id="frmSubmit">Save</button>
                        <input type="button" class="btn btn-default mr10" id="frmCancel" value="Cancel">
                    </div>
                </div>
            </div>        
            @Html.HiddenFor(x => x.InsWordID)  
        </div>
    </div>

</div>

SQL

ALTER PROCEDURE [dbo].[spViewSIG]
(
@PageSize INT = NULL,
@CurrentPage INT,      
@InsWord VARCHAR(100)

)
AS
BEGIN

    DECLARE @Skip INT
    DECLARE @Take INT    
    DECLARE @SQL VARCHAR(MAX)


IF(LEN(@InsWord)=0)
BEGIN
 SET @InsWord=null
END
else
begin
SET @InsWord='%'+@InsWord+'%'
end

SET @Skip = (@CurrentPage - 1) * @PageSize
    SET @Take = @CurrentPage * @PageSize
 
 
    SELECT * FROM (SELECT ROW_NUMBER() OVER
( ORDER BY InsWordID desc) rownumber,*
from InstructionWords
where isnull(InsWord,'') like coalesce(@InsWord,InsWord,'')
) A
      WHERE A.RowNumber > @Skip AND A.RowNumber <= @Take  

END

Tools

//dropdown
- chosen-select

$('#dropdown').val(id).trigger("chosen:updated");
$(".chosen-select").chosen();

-toastr

toastr.options = {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-right",
                    "preventDuplicates": true,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": 0,
                    "extendedTimeOut": 0,
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut",
                    "tapToDismiss": true
                }

toastr.warning('session expire , please select again', 'Warning', { timeOut: 5000 });

toastr.error('expired', 'Warning', { timeOut: 5000 });

toastr["error"]("expired , Do you want to dispose ?<br /><br /><button type='button' id='btnDisposeYes' class='btn clear' style='background-color: white;color: black;'>Yes</button><button type='button' class='btn clear' style='margin-left: 10px;background-color: white;color: black;' id='btnDisposeNo'>No</button>");

toastr.success('Record added sucessfully', 'Success', { timeOut: 5000 });
read more

Wednesday, 5 October 2016

Check if value is Int - c#

No comments
if (IsInt(Request.QueryString["mayColumn"]))
                    mayColumn = Convert.ToInt32(Request.QueryString["mayColumn"]);


 //check if value is int
        private bool IsInt(string sVal)
        {
            foreach (char c in sVal)
            {
                int iN = (int)c;
                if ((iN > 57) || (iN < 48))
                    return false;
            }
            return true;
        }
read more

Monday, 29 August 2016

Upload image from mobile

No comments
HTML

<script id="my-modal.html" type="text/ng-template">
    <ion-modal-view class="ion-nifty-modal">
        <div class="ion-modal-content-custom">
            <ion-content class="padding">
                <div id="dvGallery" style="border-bottom: 1px solid #f1f1f1;" ng-click="getPhoto();">                  
                    <img src="img/gallery.png" style="padding: 20px 20px;cursor: pointer;height: 100px;" />
                    <h3 style="display:inline;display: inline;margin-top: 35px;position: absolute;color: white;">Gallery</h3>
                </div>
                <div>&nbsp;</div>
                <div id="dvCamera" ng-click="capturePhoto();">
                    <img src="img/camera.png" style="padding: 20px 20px;cursor: pointer;height: 100px;" />
                    <h3 style="display:inline;    display: inline;margin-top: 35px;position: absolute;color: white;">Camera</h3>                  
                </div>
            </ion-content>
        </div>
    </ion-modal-view>

</script>

<ion-view view-title="Me" hide-nav-bar="true" hide-back-button="true">
    <ion-content class="post-content has-header has-subheader" delegate-handle="mainScroll">
        <div id="content">
            <div id="profile-info">              
                <canvas id="imgUser" class="divImage img-circle" style="display:none" ng-click="openModal(class)" ></canvas>              
                <img id="profile-image" class="profileImage" ng-click="openModal(class)" ng-src="http://www.healthcare4free.com/{{profile.userimageurl}}">
                <h3 id="profile-name">{{profile.firstname==null?profile.Email:profile.firstname}}</h3>
            </div>
        </div>    
    </ion-content>
</ion-view>

Controller

controller('UserProfileCtrl', ['$state', '$scope', 'RequestData', '$ionicLoading', '$ionicModal', function ($state, $scope, RequestData, $ionicLoading, $ionicModal) {
    //Model popup class define
    $scope.modalClasses = ['slide-in-up', 'slide-in-down', 'fade-in-scale', 'fade-in-right', 'fade-in-left', 'newspaper', 'jelly', 'road-runner', 'splat', 'spin', 'swoosh', 'fold-unfold'];
    //On successfully uploading image from gallry or camera
    $scope.onPhotoURISuccess = function (imageURI) {
        var canvas = document.getElementById("imgUser");
        var ctx = canvas.getContext("2d");
        var cw = canvas.width;
        var ch = canvas.height;
        var maxW = 200;
        var maxH = 200;
        var img = new Image;
        img.onload = function () {
            var iw = img.width;
            var ih = img.height;
            var scale = Math.min((maxW / iw), (maxH / ih));
            var iwScaled = iw * scale;
            var ihScaled = ih * scale;
            canvas.width = iwScaled;
            canvas.height = ihScaled;
            ctx.drawImage(img, 0, 0, iwScaled, ihScaled);
            var dataURL = canvas.toDataURL("image/jpeg");
            base64(dataURL.slice(22, dataURL.length));
        }      
        img.src = "data:image/jpeg;base64," + imageURI;      
        $('#imgUser').css('display', 'block');
        $('.profileImage').css('display', 'none');

     
        $scope.closeModal();
    }
    //get photo from galary
    $scope.getPhoto = function () {
        navigator.camera.getPicture($scope.onPhotoURISuccess, $scope.onFail, {
            quality: 50,
            destinationType: destinationType.DATA_URL,
            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
        });
    }
    //capturing photo from camera
    $scope.capturePhoto = function () {
        navigator.camera.getPicture($scope.onPhotoURISuccess, $scope.onFail, {
            quality: 50,
            destinationType: destinationType.DATA_URL
        });
    }
    //on fail of capturing or selecting image from camera
    $scope.onFail = function (message) {
        alert(message);
    }
    //open popup model
    $scope.openModal = function (animation) {
        $ionicModal.fromTemplateUrl('my-modal.html', {
            scope: $scope,
            animation: animation
        }).then(function (modal) {
            $scope.modal = modal;
            $scope.modal.show();
        });
    };
    //close popup model
    $scope.closeModal = function () {
        $scope.modal.hide();
    };
    //Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function () {
        $scope.modal.remove();
    });
    // Execute action on hide modal
    $scope.$on('modal.hidden', function () {
        // Execute action
    });
    // Execute action on remove modal
    $scope.$on('modal.removed', function () {
        // Execute action
    });
    var userId = JSON.parse(sessionStorage.UserData).UserId;
    $ionicLoading.show();
    $scope.updateUser= function ()
    {
        var canvasUser = document.getElementById("imgUser");
        var pass = canvasUser.toDataURL();
        if (pass.length > 0) {
            pass = pass.replace(/data:image\/jpeg;base64,/g, '');
            pass = pass.replace(/data:image\/png;base64,/g, '');
        }
        var promisePost= SetData.updateProfile(userId, pass);


    }


//WebAPi

 #region SaveImage
                    var bytes = Convert.FromBase64String(userResult.File);
                    string path = System.Web.HttpContext.Current.Server.MapPath("~/UserImages") + "\\" + users.UserId;

                    if (!System.IO.Directory.Exists(path))
                        System.IO.Directory.CreateDirectory(path);

                    using (var ms = new MemoryStream(bytes, 0, bytes.Length))
                    {
                        Image image = Image.FromStream(ms, true);
                        image.Save(path + "\\" + "profile.png", System.Drawing.Imaging.ImageFormat.Png);
                    }

                    #endregion

//For Ionic Model

<link href="nifty.modal.css" rel="stylesheet" />

//Model Css


.ion-nifty-modal {
  width: 90%;
  min-height: 0 !important;
  height: 300px !important;
  top: 25%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: transparent;
  border-radius: 10px;
  -webkit-box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5);
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.5); }

.ion-nifty-modal .ion-modal-content-custom {
  width: 100%;
  height: 100%;
  color: #FFF;
  background-color: #333;/*white;*/
  border-radius: 10px; }

/* Fix modal backdrop for smaller devices */
@media (max-width: 679px) {
  .active .modal-backdrop-bg {
    opacity: .5; }
  .modal-backdrop-bg {
    -webkit-transition: opacity 300ms ease-in-out;
    transition: opacity 300ms ease-in-out;
    background-color: #000;

    opacity: 0; } }
read more

Friday, 26 August 2016

Search Data From Whole Table without knowing column

No comments
CREATE  PROCEDURE [dbo].[sp_FindStringInTable]
(
 @PageSize INT = NULL,
 @CurrentPage INT,        
 @stringToFind VARCHAR(100),
 @table sysname,
 @type varchar(100),
 @columnTypeName varchar(100)  
)
AS


DECLARE @sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @cursor VARCHAR(8000)
DECLARE @Skip INT
DECLARE @Take INT

 IF(LEN(@type)<=0)
  BEGIN
   SET @type=NULL
  END
 IF(LEN(@columnTypeName)<=0)
  BEGIN
   SET @columnTypeName=NULL
  END

 SET @Skip = (@CurrentPage - 1) * @PageSize
SET @Take = @CurrentPage * @PageSize


BEGIN TRY

   SET @sqlCommand = 'SELECT *,(select typeName from address_types where address_types.type_id=A.type_id) as typeName
   FROM
   (SELECT ROW_NUMBER() OVER
   (ORDER BY add_id desc) rownumber,* FROM [' + @table + '] WHERE'
   SET @where = ''  
   SET @cursor = 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
   FROM ' + DB_NAME() + '.INFORMATION_SCHEMA.COLUMNS WHERE  
    TABLE_NAME = ''' + @table + '''
   AND DATA_TYPE IN (''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'  

   EXEC (@cursor)

   OPEN col_cursor  
   FETCH NEXT FROM col_cursor INTO @columnName  

   WHILE @@FETCH_STATUS = 0  
   BEGIN  
       IF @where <> ''
           SET @where = @where + ' OR'

       SET @where = @where + ' [' + @columnName + '] LIKE ''%' + @stringToFind + '%'''
  IF(LEN(@columnTypeName)>0)
    BEGIN
  SET @where=@where+' AND '+@columnTypeName+'='+COALESCE(@type,'[type_id]')+''
     END  
       FETCH NEXT FROM col_cursor INTO @columnName  
   END  

   CLOSE col_cursor  
   DEALLOCATE col_cursor

   SET @sqlCommand = @sqlCommand + @where +') A WHERE
   A.RowNumber > ' + Cast(@Skip AS VARCHAR) + ' AND A.RowNumber <= '+cast(@Take as varchar)
 
   EXEC (@sqlCommand)
END TRY
BEGIN CATCH
   PRINT 'There was an error. Check to make sure object exists.'
   PRINT error_message()
   
   IF CURSOR_STATUS('variable', 'col_cursor') <> -3
   BEGIN
       CLOSE col_cursor  
       DEALLOCATE col_cursor
   END
END CATCH
read more

Wednesday, 24 August 2016

Dynamic sql query

No comments
CREATE procedure [dbo].[GetAll]
(
@countryId int,
@Title varchar(max),
@City varchar(max),
@MinimumInvestment int=null,
@MaximumInvestment int=null,
@InvestorRoleId int,
@GrowthStage varchar(max)
)
as
begin
declare @Query varchar(max)
set @Query ='
 select * from [dbo].[Opportunities]
where
CountryId =isnull('+case when @countryId is null then 'NULL' else cast(@countryId as varchar) end+',CountryId)
and City  like isnull('+case when @City is null then 'NULL' else cast(@City  as varchar) end+',City)
and Title  like isnull('''+case when @Title is null then 'NULL' else cast(@Title as varchar) end+''',Title)
and MinimumInvestment>=isnull('+case when @MinimumInvestment is null then 'NULL' else cast(@MinimumInvestment  as varchar) end+',MinimumInvestment)
and MaximumInvestment>=isnull('+case when @MaximumInvestment is null then 'NULL' else cast(@MaximumInvestment  as varchar) end+',MaximumInvestment)
and InvestorRoleId = '+cast(@InvestorRoleId as varchar) +'
and GrowthStageId in ('+case when @GrowthStage is null then 'GrowthStageId' else @GrowthStage end+')'

execute(@Query)
end
read more

Tuesday, 23 August 2016

Pagination in mvc with sql with Jquery datatable sorting

No comments
SQL




CREATE PROCEDURE soFoo
(
@PageSize INT = NULL,
@CurrentPage INT,      
@firstname VARCHAR(50),
@lastname VARCHAR(50),
@providerid int,
@clientid int ,
@patientChart  VARCHAR(50) ,
@status int
)
AS
BEGIN

    DECLARE @Skip INT
    DECLARE @Take INT    
    DECLARE @SQL VARCHAR(MAX)

if(@providerid <= 0)
    BEGIN
SET @providerid =null
    END
if(@status < 0)
    BEGIN
SET @status=null
    END


IF(LEN(@lastname)=0)
BEGIN
 SET @lastname=null
END
else
begin
SET @lastname='%'+@lastname+'%'
end

SET @Skip = (@CurrentPage - 1) * @PageSize
    SET @Take = @CurrentPage * @PageSize
 
 
    SELECT *,(select statename from states where states.stateid=A.stateid) as statename  FROM (SELECT ROW_NUMBER() OVER
( ORDER BY IsActive desc) rownumber,*
from Patient
where isnull(firstname,'') like coalesce(@firstname,firstname,'')
and isnull(lastname,'') like coalesce(@lastname,lastname,'')
and patientChart = coalesce(@patientChart,patientChart,'')
and IsActive=coalesce(@status,IsActive,'')
AND Patient.clientid=@clientid
) A
      WHERE A.RowNumber > @Skip AND A.RowNumber <= @Take  
END


Controller


 public void Get(Models models)
        {
            int _currentPage = 1;
            DateTime Fromdate = DateTime.Now;
            Fromdate = Fromdate.AddDays(-30);
            DateTime Todate = DateTime.Now;
            string lotno = string.Empty;
            int PageSize = 7;
            int printInId = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["printInId"]))
            {
                if (IsInt(Request.QueryString["printInId"]))
                    printInId = Convert.ToInt32(Request.QueryString["printInId"]);
            }
            if (!int.TryParse(Request.QueryString["pg"], out _currentPage))
            {
                _currentPage = 1;
            }
            if (!string.IsNullOrEmpty(Request.QueryString["fromDate"]))
            {
                Fromdate = Convert.ToDateTime(Request.QueryString["fromdate"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["toDate"]))
            {
                Todate = Convert.ToDateTime(Request.QueryString["toDate"]);
            }
models.CurrentPage = _currentPage;
            var relRepository = uow.Repository<RelRepository>();
            var result =RelRepository.ExecWithStoreProcedure("spView @PageSize,@CurrentPage,@FromDate,@ToDate,@lotno,@clientid,@printInId",
                new SqlParameter("PageSize", SqlDbType.Int) { Value = PageSize },
                new SqlParameter("CurrentPage", SqlDbType.Int) { Value = _currentPage },
                new SqlParameter("FromDate", SqlDbType.DateTime, 100) { Value = Fromdate },
                new SqlParameter("ToDate", SqlDbType.DateTime, 100) { Value = Todate },              
                new SqlParameter("printInId", SqlDbType.Int) { Value = printInId }
                ).ToList();

            models.TotalRecordCount = (RelRepository.ExecWithStoreProcedure("spViewCount @FromDate,@ToDate,@printInId",
                new SqlParameter("FromDate", SqlDbType.DateTime, 100) { Value = Fromdate },
                new SqlParameter("ToDate", SqlDbType.DateTime, 100) { Value = Todate },             
                new SqlParameter("printInId", SqlDbType.Int) { Value = printInId }
                ).FirstOrDefault().TotalRecordCount);


            int pageCount = models.TotalRecordCount / PageSize;
            pageCount = models.TotalRecordCount % PageSize > 0 ? pageCount + 1 : pageCount;
            models..TotalPageCount = pageCount;
            models..lstDrugIn = result;

VIEW

<div class="box">
                        <!-- /.box-header -->
                        <div class="box-body no-padding">
                            <div class="row col-md-12">
                                <div class="col-md-6 no-padding">                                   
                                    <div class="col-md-3 no-padding" style="padding-left: 5px !important;">
                                        <label>
                                            <input type="text" id="txtDatepickerFrom" class="form-control datePicker" placeholder="From Date" />
                                        </label>
                                    </div>
                                    <div class="col-md-3 no-padding" style="padding-left: 5px !important;">
                                        <label>
                                            <input type="text" id="txtDatepickerTo" class="form-control datePicker" placeholder="To Date" />
                                        </label>
                                    </div>                                   
                                </div>
                                <div class="col-md-6 no-padding">
                                    <div class="col-md-8"  style="padding-left: 5px !important;">
                                        <label style="width:100%">
                                            @Html.DropDownListFor(m => m.drugid, Model.DrugList, "Select Drug", new { @class = "chosen-select", id = "dropDrugName", name = "drpList" })
                                        </label>
                                    </div>
                                    <div class="col-md-4 no-padding">
                                        <label>
                                            <button class="btn btn-primary" id="btnSearch" onclick="SearchData('search');return false;">Search</button>
                                            <button class="btn btn-primary" id="btnReset" onclick="SearchData('reset');return false;">Reset</button>
                                        </label>
                                    </div>
                                </div>                                                                                            
                            </div>

                            <div class="clearfix">&nbsp;</div>

                            <div class="row col-sm-12">

                                <table id="tableView" class="table tablesorter">
                                    <thead>
                                        <tr>                                        
                                            <th class="textRight">
                                                Price
                                            </th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var item in @Model.lstDrugIn)
                                        {
                                            <tr>                                                
                                                <td style="text-align:right">@item.balanceqty</td>               
                                                <th class="col-md-2">
                                                </th>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>

                        </div>
                        <div class="box-footer">                           
                            <ul class="pagination pagination-sm no-margin pull-right">
                                @if (Model.CurrentPage > 1)
                                {
                                    <li>
                                        <a href="?pg=@(Model.CurrentPage > 1 ? (Model.CurrentPage - 1) : Model.CurrentPage)&fromDate=@(Request.QueryString["fromDate"] != null ? Request.QueryString["fromDate"] : "")&toDate=@(Request.QueryString["toDate"] != null ? Request.QueryString["toDate"] : "")">&laquo;</a>
                                    </li>
                                }
                                else
                                {
                                    <li class="disabled">
                                        <a href="javascript:void(0);">&laquo;</a>
                                    </li>
                                }
                                @if (Model.TotalPageCount > 0)
                                {
                                    for (int i = (Model.CurrentPage > 3 ? (Model.CurrentPage - 2) : 1); i < (Model.CurrentPage > 3 ? (Model.CurrentPage) + 3 : 6); i++)
                                    {
                                        if (Model.TotalPageCount >= i)
                                        {
                                            <li class="@(i == (Model.CurrentPage) ? "active" : "")">
                                                <a class="@(i == (Model.CurrentPage) ? "selected" : "")" href="?pg=@i&fromDate=@(Request.QueryString["fromDate"] != null ? Request.QueryString["fromDate"] : "")&toDate=@(Request.QueryString["toDate"] != null ? Request.QueryString["toDate"] : "")">@(i)</a>
                                            </li>
                                        }
                                    }
                                }
                                @if (Model.CurrentPage < Model.TotalPageCount)
                                {
                                    <li>
                                        <a href="?pg=@(Model.TotalPageCount == Model.CurrentPage ? (Model.TotalPageCount).ToString() : (Model.CurrentPage + 1).ToString())&fromDate=@(Request.QueryString["fromDate"] != null ? Request.QueryString["fromDate"] : "")&toDate=@(Request.QueryString["toDate"] != null ? Request.QueryString["toDate"] : "")">&raquo;</a>
                                    </li>
                                }
                                else
                                {
                                    <li class="disabled"><a href="javascript:void(0);">&raquo;</a></li>
                                }
                            </ul>
                        </div>
                        <!-- /.box-body -->
                    </div>


JQUERY


function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                    results = regex.exec(location.search);
                return results === null ? 0 : decodeURIComponent(results[1].replace(/\+/g, " "));
            }

 var drugName = getParameterByName('drugName');

                if (dateFrom.length > 0) {
                    $('#datepickerFrom').val(dateFrom);
                }


        $('#tableView').DataTable({
            "paging": false,
            "ordering": true,
            "info": false,
            "bFilter": false,
            "bInfo": false,
            "aaSorting": [[0, 'desc']]
        });
        $('#txtPrintInId').on('change', function () {           
            SearchData('Print');
        });
read more