Showing posts with label mvc. Show all posts
Showing posts with label mvc. Show all posts

Wednesday, 12 April 2017

Send Push Notification With Cordova And Webapi

No comments
Cordova Plugin

https://github.com/phonegap/phonegap-plugin-push

Push Plugin


var push = PushNotification.init({
           android: {
               senderID: "628523812525"
           },
           browser: {
               pushServiceURL: 'your url'
           },
           ios: {
               alert: "true",
               badge: "true",
               sound: "true"
           },
           windows: {}
       });
       PushNotification.hasPermission(function (permissionResult) {
          if (permissionResult.isEnabled) {           
            push.on('registration'function (data) {
              alert(data.registrationId,data.registrationId);          
            });
 
            push.on('notification'function (data) {
              alert(JSON.stringify(data));
            });
 
            push.on('error'function (e) {      
              alert("e.message: " + e.message);
            });
          }
        });
      

WebAPI

//RegisterId you got from Android Developer.
string deviceId = "APA91bExfJOpM0vmKW8q200RSPs5iSPugD1mKf4PSYaFaz5TyZP2QYwmYUCDVHdNV7";
 
string message = "Demo Notification";
string tickerText = "Patient Registration";
string contentTitle = "Titlesss";
string postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
  "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
             "\"contentTitle\":\"" + contentTitle + "\", " +
             "\"message\": \"" + message + "\"}}";
 
//  
//  MESSAGE CONTENT  
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 
//  
//  CREATE REQUEST  
HttpWebRequest Requests = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Requests.Method = "POST";
//  Request.KeepAlive = false;  
 
Requests.ContentType = "application/json";
Requests.Headers.Add(string.Format("Authorization: key={0}""AIzaSyBKz7u6jeat1p09cO1"));
Requests.ContentLength = byteArray.Length;
 
Stream dataStream = Requests.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
 
//  
//  SEND MESSAGE  
 
WebResponse Response = Requests.GetResponse();
 
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
    var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
    var text = "Response from web service isn't OK";
}
 
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
 
 
read more

Friday, 31 March 2017

Redirect To Another Page If User Have No Right TO Access Page

No comments
public class ValidateUserAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (SessionFactory.Instance.CurrentUsers == null)
                filterContext.Result = new RedirectResult(string.Format("/Home/Login?ReturnUrl={0}"HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)));
            else if (SessionFactory.Instance.CurrentUsers.clientid == 0)
                filterContext.Result = new RedirectResult(string.Format("/Home/Login"HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)));
        }
    }
 
    public class ValidateSetupAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (SessionFactory.Instance.CurrentUsers.roleid == (int)Constant.Roles.user)
                filterContext.Result = new RedirectResult(string.Format("/Dashboard/Dashboard"HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)));
        }
    }




Controller

[ValidateUser]
[ValidateSetup]
public class MasterController : Controller
{
}
read more

Sunday, 26 March 2017

Delete Multiple Items With Checkbox MVC

No comments
JQUERY

$('#selectAllCheck').click(function (e) {
                   var table = $(e.target).closest('table');
                   $('td input:checkbox', table).prop('checked'this.checked);
               });

function Inactivate() {
                debugger
                var mainForm = $("#frmDrugsView");
                var serializeData = JSON.stringify(mainForm.serializeArray());
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Inactivate", "Master")",
                    data: "{ 'jsonString': '" + serializeData.toString() + "' }",
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (responseData) {
                        debugger
                        location.reload();
                    },
                    error: function (e) {
                         
                    }
                });
            }


HTML

@using (@Html.BeginForm(nullnullFormMethod.Post, new { id = "frmDrugsView", @class = "form-horizontal bordered-group", role = "form" }))
{
<table class="table">
<tr>
 <th><input type="checkbox" id="selectAllCheck" /></th>                                            
</tr>
@foreach (var item in @Model.lstDrugRel)
 {
   <tr class='@(item.IsActive==false?"deletedPatient":"")'>
   <td><input type="checkbox" name="inactiveDrug" id="inactiveDrug" value="@item.drugid" />
   </td>                                               
   </tr>
 }
</table>
<input type="submit" class="btn btn-primary " id="btnInactive" value="Save" 
onclick="Inactivate();return false;">
}                 

Controller


//Inactivate Drugs
        public ActionResult Inactivate(string jsonString)
        {
            List<serializeJsonRequest> serializeJsonRequest = JsonConvert.DeserializeObject<List<serializeJsonRequest>>(jsonString); 
            foreach (var item in serializeJsonRequest)
            {
                if (item.name == "inactiveDrug")
                {
                    var drugRepository = uom.Repository<DrugRepository>();
                    var drugData = drugRepository.GetDrugById(int.Parse(item.value));
                    drugData.IsActive = false;
                    drugRepository.UpdateDrug(drugData);
                }
            }
            return Json("Sucess"JsonRequestBehavior.AllowGet);
        }
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

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

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