Saturday, 26 December 2015

Export Data in sql data base

aspx page

   <asp:FileUpload ID="file_upload" runat="server" />
        <asp:Button ID="btn_upload" runat="server" OnClick="btn_upload_Click" Text="Upload" />

.cs

   protected void btn_upload_Click(object sender, EventArgs e)
        {
            string fileName = Server.MapPath("~/CSVFILE/") + Path.GetFileName(file_upload.PostedFile.FileName);
            file_upload.SaveAs(fileName);
         

            string csvData = File.ReadAllText(fileName);
                
       int index= csvData.IndexOf('\n');
         csvData=  csvData.Substring(index);
         BAL_Import objbal = new BAL_Import();
      int result= objbal.Import(csvData);
      if (result == 1)
      {
          Response.Write("successfully");
      }
      else {
          Response.Write("Try again");
     
      }
        }

BAL

 public int Import(string csvData)
        {
            DAL_Import objDal = new DAL_Import();

            DataTable dt = new DataTable();

            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });

              foreach (string row in csvData.Split('\n'))
                 {
            if (!string.IsNullOrEmpty(row))
            {
              dt.Rows.Add();
              int i = 0;
              foreach (string cell in row.Split(','))
              {
                    dt.Rows[dt.Rows.Count - 1][i] = cell;
                  i++;
              }
          }
         }
         int result= objDal.Import(dt);
         return result;
        }
DAL

public int Import(DataTable dt)
        {

            string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

            SqlParameter[] prm = new SqlParameter[1];
            prm[0] = new SqlParameter("@detail", dt);

            int result = Convert.ToInt32(SqlHelper.ExecuteScalar(connStr, CommandType.StoredProcedure, "usp_insertDataTable", prm));
            return result;

        }

Store Procedure

ALTER PROCEDURE usp_insertDataTable
    (
    @detail MyTableType READONLY
   
    )AS
BEGIN
        SET NOCOUNT ON;
    insert into tbl_customerDetail(customer_id,customer_name,country)
    select customer_id,customer_name,country from @detail;
    select 1
    END
GO



CREATE TABLE TYPE


CREATE TYPE [dbo].[MyTableType] AS TABLE(
    customer_id int NOT NULL,
    customer_name [nvarchar](50) NULL,
    country nvarchar(50) NULL
)

FOR XML FILE UPLOAD
http://www.aspsnippets.com/Articles/Insert-Upload-XML-file-Data-into-SQL-Table-using-Stored-Procedure-in-ASPNet-using-C-VBNET.aspx

Wednesday, 22 July 2015

Get week dates of current year


Current week of current year
select datepart(dw, getdate()) as CurrentWeek 
first date of Current week  in current year
 select dateadd(day, 1-datepart(dw, getdate()), getdate())
last date of Current week  in current year
 select dateadd(day, 1-datepart(dw, getdate())+6, getdate())

Saturday, 25 April 2015

JSON Implementation

Page name ::

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PackageList.aspx.cs" Inherits="json.PackageList" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   <%-- <script src="js/jquery.min.js"></script>--%>
 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <script src="js/SearchPackage.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div class="container">
         
        <!-- leftcontent -->
        <div class="row" style="height:250px;">
            <div class="span7 well">
                 <div class="" style="float:left">
                    <div id="golftitle" >
                        <span style="font-family:Calibri;font-size:5px;"></span>
                    </div>
                    <div id="divList">
                    </div>
                    <div id="paginglist">
                    </div>
                </div>
             </div>
                 <div class="span4">
                 
                    <div class="well" >      
                        <h5 >
                            Golf Packages By City:</h5><hr/>
                        <ul id="ul_cityList">
                        </ul>
                    </div>
                </div>
         </div>
       </div>
    </div>
        <asp:HiddenField ID="hdnTourID" runat="server" />
    <asp:HiddenField ID="hdnPageID" runat="server" />
    <asp:HiddenField ID="hdnCountryID" runat="server" />
    <asp:HiddenField ID="hdnStateID" runat="server" />
    <asp:HiddenField ID="hdnCityID" runat="server" />

    </form>
</body>
</html>

.CS

protected void Page_Load(object sender, EventArgs e)
        {


            hdnCountryID.Value ="0";
            hdnStateID.Value = "0";
            hdnCityID.Value = "0";
            int page = 0;
            if (page == 0)
            {
                hdnPageID.Value = "1";
            }
            else
            {
                hdnPageID.Value = page.ToString();
            }

        }


Web Service  in  service folder as

package.asmx


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Data;
using System.Text;
using System.Web.Script.Services;



using System.Web.Services.Protocols;
using System.Xml.Linq;



namespace json.service
{
    /// <summary>
    /// Summary description for package
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     [System.Web.Script.Services.ScriptService]
    public class package : System.Web.Services.WebService
    {

        
             [WebMethod]
       public string[] SearchPackage(int cid, int sid, int cityid, int page)
        {
            try
            {
                string[] json = new string[3];
                DAL.SearchPageDAL dal = new DAL.SearchPageDAL();
                DataSet ds = dal.SearchPages(cid, sid, cityid, page);
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    json[0] = string.Empty;
                    json[1] = string.Empty;
                    json[2] = string.Empty;

                    return json;
                }
                else
                {
                    json[0] = Util.GetJsonString(ds.Tables[0]);
                }
                if (ds.Tables[1].Rows.Count > 0)
                {
                    int count = Convert.ToInt32(ds.Tables[1].Rows[0]["total"].ToString());
                    int mode = count % 4;
                    if (mode > 0)
                    {
                        mode = 1;
                    }
                    int totalpage = count / 4;

                    json[1] = (totalpage + mode).ToString();
                    json[2] = count.ToString();
                }
                else
                {
                    json[1] = string.Empty;
                    json[2] = string.Empty;
                }
                return json;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
  

DAL 


  public  DataSet SearchPages(int CountryID, int StateID, int CityID, int PageName)
        {


            string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

            SqlParameter[] prm = new SqlParameter[4];
            prm[0] = new SqlParameter("@CountryID", CountryID);

            prm[1] = new SqlParameter("@StateID", StateID);

            prm[2] = new SqlParameter("@CityID", CityID);
            prm[3] = new SqlParameter("@pageID", PageName);
               DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.StoredProcedure, "rw_usp_SearchPackage", prm);
            return ds;
            
            
        }
Util that stringfy   data set into json format

     public static string GetJsonString(DataTable dt)
        {
            string json = "[";
            int count = 0;
            foreach (DataRow row in dt.Rows)
            {
                count++;
                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                Newtonsoft.Json.JsonWriter jsonWriter = jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw);
                jsonWriter.WriteStartObject();
                foreach (DataColumn column in dt.Columns)
                {
                    jsonWriter.WritePropertyName(column.ColumnName);
                    jsonWriter.WriteValue(row[column]);
                }
                if (count == dt.Rows.Count)
                {
                    json = json + sw.ToString() + "}";
                }
                else
                {
                    json = json + sw.ToString() + "},";
                }
                jsonWriter.WriteEndObject();
                sw.Close();
            }
            json = json + "]";
            return json;
        }


JS that show  value  return by webservice


var _CountryID = 0; var _StateID = 0; var _CityID = 0; var _pageID = 0; var _SearchText='';
var _TourID = 0;
$(document).ready(function () 
{
    
    try {
        _CountryID = $('#hdnCountryID').val();
         _StateID = $("#hdnStateID").val();
        _CityID = $('#hdnCityID').val();
         _pageID = $('#hdnPageID').val();
        _SearchText = $('#hdnSearchText').val();
       LoadResults();
    }
    catch (Error) {
        alert(Error);
    }
});

function LoadResults() {
  
    try {
        var urlgetcode = 'service/package.asmx/SearchPackage';
        $.ajax({
            type: "POST",
            url: urlgetcode,
            data: '{cid:"' + _CountryID + '",sid:"' + _StateID + '",cityid:"' + _CityID + '",page:"' + _pageID + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                try {

                                        if (msg.d[0] == '') {
                        $('#divList').before('<h2>No Golf found.</h2>Sorry, no Golf matched found in this country. View all Golf');
                        return;
                    }

                    var obj = jQuery.parseJSON(msg.d[0]);
                    var list = '';
                    for (i = 0; i < obj.length; i++) {
                          $page = $('<div>').html(obj[i].pagename);
                        if (i == 0 && _CountryID != 0) {
                            $('#golftitle').append('<h1>Golf IN <span id="place">' + obj[i].destination + ' </span></h1>');
                        }
                        else if (i == 0 && _CountryID == 0) {
                            $('#golftitle').append('<h1>View All Golf Travel</h1>');
                        }
                        list = list + '<div > ';
                        list = list + '<div >';
                        list = list + '<a href="offer-detail.aspx?id=' + obj[i].id + '"><img style="width:235px;height:165px;" src="images/ImgProduct/' + obj[i].photo + '" alt=""><span >View More Details</span></a>';
                        list = list + '</div>';
                        list = list + '<div >';
                        list = list + '<div >';
                        list = list + '<h2><a href="offer-detail.aspx?id=' + obj[i].id + '">' + obj[i].holiday + '</a></h2>';
                            list = list + '</div>';
                        list = list + '<div >';
                        list = list + $page.find("p:lt(2)").text(); ;
                        list = list + '</div>';
                        list = list + '</div>';
                        list = list + '<div class="re-bot">';
                           list = list + '<a href="offer-detail.aspx?id=' + obj[i].id + '"  title="">' + obj[i].CityName + '</a> ';
                        list = list + '<a href="offer-detail.aspx?id=' + obj[i].id + '" title="">Photos</a>';
                        list = list + '</div>';
                        list = list + '<div ></div>';
                        list = list + '</div>';
                             }
                    $('#divList').before(list);
                    $('.count').append(parseInt(msg.d[2]) + ' available offers');
                    if (parseInt(msg.d[1]) <= 1) return;
                 var redirecturl = '&id=' + _CountryID + '&state=' + _StateID + '&city=' + _CityID;
                    var pageing = '<div ><div ><span >Pages :';
                      for (i = 1; i <= msg.d[1]; i++) {
                         if (_pageID == i) {
                               pageing = pageing + '<strong >' + _pageID + '</strong>';
                           }
                        else {
                            pageing = pageing + '<strong><a  href="Golf-list.aspx?page=' + i + redirecturl + '">' + i + '</a></strong>';
                        }
                    }
                     pageing = pageing + '</span></div>  <div ></div> </div>';

                    $('#paginglist').append(pageing);

                }
                catch (Error) {

                    alert(Error);
                }
            },
            error: function (request) {
                alert(request.responseText);
            }
        });
    }
    catch (Error) {
          alert(Error);
    }
   }


References Added

Newtonsoft.Json
   
















Wednesday, 1 April 2015

conditional delete to check value by temp table sql

ALTER PROCEDURE [dbo].[sp_deletecustcash]
-- Add the parameters for the stored procedure here
(@cid int,
@cashid int
)AS
BEGIN
SET NOCOUNT ON;
declare @mulcashid table(mulCASHid int)
insert into @mulcashid select Cash_ID from Cash_Details where Cust_ID= @cid

if exists(select mulCASHid from @mulcashid where mulCASHid <> @cashid)
begin
    delete from Cash_Details where Cash_ID=@cashid
delete from SUB_DETAILS where Cash_ID=@cashid and Cust_ID=@cid
end
else
begin

delete from Customer_Master where Cust_ID=@cid
delete from Cash_Details where Cash_ID=@cashid
delete from SUB_DETAILS where Cash_ID=@cashid and Cust_ID=@cid

end

END








ALTER PROCEDURE [dbo].[sp_GetAmountDetail]
-- Add the parameters for the stored procedure here
(
@uderid int
)
AS
BEGIN
SET NOCOUNT ON;

    -- Insert statements for procedure here
declare @tdcode3 varchar(100)
set @tdcode3 = (SELECT case when CONVERT(varchar(20), (SUM(AeCAmount)-SUM(AeDAmount)))>=0 then '$'+ convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount)))+'.00' else
'($'+REPLACE( convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount))),'-','')+'.00)'

end  from AmountEnter where Aetraderid=1 and TdCode=3 group by Aetraderid

)



declare @tdcode2 varchar(100)

set @tdcode2=( SELECT case when CONVERT(varchar(20), (SUM(AeCAmount)-SUM(AeDAmount)))>=0 then '$'+ convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount)))+'.00' else
'($'+ REPLACE(convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount))),'-','')+'.00)'

end from AmountEnter where Aetraderid=1 and TdCode=2 group by Aetraderid)

declare @tdcode5 varchar(100)


set @tdcode5=(
SELECT case when CONVERT(varchar(20), (SUM(AeCAmount)-SUM(AeDAmount)))>=0 then '$'+ convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount)))+'.00' else
'($'+ REPLACE( convert(varchar(10),(SUM(AeCAmount)-SUM(AeDAmount))),'-','')+'.00)'

end from AmountEnter where Aetraderid=1 and TdCode=5 group by Aetraderid
)




declare @maintd decimal(18,2);

if((select PATINDEX('%$%','($100.00)'))=2)

set @maintd=(select REPLACE( REPLACE('($100.00)' ,'($','-'),')',''))
else if((select PATINDEX('%$%','($100.00)'))=1)
set @maintd=(select REPLACE( REPLACE('$100.00' ,'$','+'),')',''))
else
set @maintd=0.00
print @maintd



create  table #temp(
tdcode3 varchar(100),
tdcode2 varchar(100),
tdcode5 varchar(100)
)
insert into #temp values(@tdcode3,@tdcode2,@tdcode5)
select * from #temp
drop table #temp
END




main data by PATIINDEX

declare @maintd decimal(18,2);
declare @tdcode3forreplace varchar(100)
declare @tdcode31 varchar(100)
set @tdcode31 = (SELECT case when CONVERT(varchar(20), ISNULL((SUM(AeCAmount)-SUM(AeDAmount)),0))>=0 then '$'+ convert(varchar(10),ISNULL((SUM(AeCAmount)-SUM(AeDAmount)),0))+'.00' else
'($'+REPLACE( convert(varchar(10),ISNULL((SUM(AeCAmount)-SUM(AeDAmount)),0)),'-','')+'.00)'

end  from AmountEnter where Aetraderid=1 and TdCode=3 group by Aetraderid

)

if((select PATINDEX('%$%',@tdcode31))=2)

set @maintd=(select REPLACE( REPLACE(@tdcode31 ,'($','-'),')',''))
else if((select PATINDEX('%$%',@tdcode31))=1)
set @maintd=(select REPLACE( REPLACE(@tdcode31 ,'$','+'),')',''))
else
set @maintd=0.00
print @maintd


Crazy developer.com




Sunday, 1 February 2015

Auto Complete text box by jquery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"/>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css"/>  
   
     <script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest1").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "autocomplete.aspx/Autocomplete",

                        data: "{'search':'" + $('#<%=txtsearch.ClientID %>').val() + "'}",
                        dataType: "json",
                        success: function (data) {
                                  response($.map(data.d, function (item) {
                               
                                return {
                                    label: item.split('/')[1],
                                    val: item.split('/')[0]
                                 
                                }
                               
                            }));
                            },
                                error: function (result) {
                                    alert("please enter other value");
                                }
                     
                    });
                 
                },
                select: function(event, ui) {
                    $('#lblUserId').text(ui.item.val);
                    $('#hdnId').val(ui.item.val);
                   
                }
            });
        }
     
</script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hdnId" runat="server" />
            <input type="text" id="txtsearch" class="autosuggest1" runat="server"/>
        <div>
Selected UserId:<b><label id="lblUserId" /></b>
</div>
        <asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClientClick="checkhdnvalue();" OnClick="btnsubmit_Click" />
       </div>
    </form>
</body>
</html>
[WebMethod]
        public static List<string> Autocomplete(string search)
        {int i;
            List <string> result= new List<string>();
               //  int _totalrowcount = 0;
                string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
                   SqlParameter[] prm = new SqlParameter[1];
                prm[0] = new SqlParameter("@search", search);

                DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.StoredProcedure, "sp_autocomplete", prm);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        result.Add(ds.Tables[0].Rows[i][0].ToString() + '/' + ds.Tables[0].Rows[i][1].ToString());
                    }
                }
                else {
                    result.Add("0/no record found");
                }
                return result;
       
        }

        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            if (hdnId.Value =="0")
            {
                Response.Write("plesase enter value");

                txtsearch.Value = String.Empty;
            }
        }