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