Sunday, December 6, 2015

Hogan.js example 1

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>hogan.js example</title>
</head>
<body>

    <div id="employeeInfo"></div>
<div id="employeeInfodetails"></div>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/hogan.js/2.0.0/hogan.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
var data=[];
$(document).ready(function() {

   var templateemployeeInfo = Hogan.compile(
'Name - <input type="text" id="txtname" />' +
'<br/><br/>' +
'Mobile - <input type="text" id="txtmobile" />' +
'<br/><br/>' +
'Email - <input type="text" id="txtemail" />' +
'<br/><br/>' +
'<input type="button" id="btnsubmit" value="Submit"/>'+
'<input type="button" id="btnedit" value="Edit"/>'
);
var employeeInfo = templateemployeeInfo.render(data);
document.getElementById('employeeInfo').innerHTML = employeeInfo;

$('#btnsubmit').click(function(){

var txtname = $('#txtname').val();
var txtmobile = $('#txtmobile').val();
var txtemail = $('#txtemail').val();

data.push({
name : txtname,
mobile : txtmobile,
email : txtemail
});


});

$('#btnedit').click(function(){

var templateemployeeInfodetails = Hogan.compile(
'Name - <input type="text" id="txtname" value={{name}}></input>' +
'<br/><br/>' +
'Mobile - <input type="text" id="txtmobile" />' +
'<br/><br/>' +
'Email - <input type="text" id="txtemail" />' +
'<br/><br/>' +
'<input type="button" id="btnsubmit" value="Submit"/>'+
'<input type="button" id="btnedit" value="Edit"/>'
);
var employeeInfodetails = templateemployeeInfodetails.render(data[0]);
document.getElementById('employeeInfodetails').innerHTML = employeeInfodetails;

});

});      
   
    </script>
</body>
</html>

Tuesday, November 17, 2015

jquery nested json example

 shareNoteDocumentJson.push({
                    userId: '1',
                    notes: [
                        { noteId: 'n1', note: 'note1' },
                        { noteId: 'n2', note: 'note2' },
                        { noteId: 'n3', note: 'note3' },
                    ],
                    documents: [
                        { documentId: 'd1', document: 'document1' },
                        { documentId: 'd1', document: 'document2' },
                        { documentId: 'd1', document: 'document3' },
                    ]
                });

jquery check if radiobutton is checked

 if($('#radio_button').is(':checked')) { alert("it's checked"); }

Monday, November 16, 2015

jquery radio button checked event by name

  $('input:radio[name="share"]').change(function () {
                alert(this);
            });

Friday, October 30, 2015

Remove duplicate objects in an array of object in JavaScript

function remove_duplicates(objectsArray) {
    var usedObjects = {};

    for (var i=objectsArray.length - 1;i>=0;i--) {
        var so = JSON.stringify(objectsArray[i]);

        if (usedObjects[so]) {
            objectsArray.splice(i, 1);

        } else {
            usedObjects[so] = true;          
        }
    }

    return objectsArray;

}

Monday, September 28, 2015

telrik kendo grid edit command event javascript

 command: [{ name: "edit", text: "edit", click: myFunction }, "destroy"],

function myFunction(e) {
    alert("deleted pressed!");
}

Start Task Scheduler

To Run Task Scheduler using the Windows interface

  1. Click the Start button.
  2. Click Control Panel .
  3. Click System and Maintenance .
  4. Click Administrative Tools .
  5. Double-click Task Scheduler .

To Run Task Scheduler from the Command Line

  1. Open a command prompt. To open a command prompt, click Start , click All Programs , click Accessories , and then click Command Prompt .
  2. At the command prompt, type Taskschd.msc .

SQL alter table modify column

ALTER TABLE Persons
ALTER COLUMN DateOfBirth year

Thursday, September 24, 2015

asp.net create menu from datatable

public static string CrateMenuFromDT(DataTable dt)
        {
            string retstring = "";


            DataRow[] drparentMain = dt.Select("ParentID =0 OR ParentID is null");

            foreach (DataRow dr in drparentMain)
            {
                string strmenuselect = Convert.ToString(dr["selected"]) == "0" ? "menu_nonselected" : "menu_selected";
                string strsubmenu = "";


                DataRow[] drparentMenu = dt.Select("ParentID =" + Convert.ToString(dr["MenuID"]));
                foreach (DataRow pdr in drparentMenu)
                {
                    if (strsubmenu == "")
                        strsubmenu = " <div class='submenu_straight'><ul><li><a href='" + Convert.ToString(pdr["navigateurl"]) + "' class='parent'><p>" + Convert.ToString(pdr["Text"]) + "</p></a></li>";
                    else
                        strsubmenu = strsubmenu + "<li><a href='" + Convert.ToString(pdr["navigateurl"]) + "' class='parent'><p>" + Convert.ToString(pdr["Text"]) + "</p></a></li>";
                }

                if (strsubmenu != "")
                    strsubmenu = strsubmenu + "</ul></div>";


                if (retstring == "")
                    retstring = "<li class='" + strmenuselect + "'><p><a href='" + Convert.ToString(dr["navigateurl"]) + "'>" + Convert.ToString(dr["Text"]) + "</a></p>" + strsubmenu + "</li>";
                else
                    retstring = retstring + "<li class='" + strmenuselect + "'><p><a href='" + Convert.ToString(dr["navigateurl"]) + "'>" + Convert.ToString(dr["Text"]) + "</a></p>" + strsubmenu + "</li>";

            }

            return retstring;
        }

asp.net show user zone date

       public static string ShowUserZoneDate(DateTime Dbdate, double zone)
        {
            if (Dbdate != null)
            {
                TimeSpan tms = new TimeSpan(0, Convert.ToInt32(zone * 60), 0);
                return Dbdate.Add(tms).ToString();
            }
            else
                return "";
        }

        public static string ShowUserZoneDate(string IDbdate, double zone)
        {
            if (!string.IsNullOrEmpty(IDbdate))
            {
                DateTime Dbdate = Convert.ToDateTime(IDbdate);
                TimeSpan tms = new TimeSpan(0, Convert.ToInt32(zone * 60), 0);
                return Dbdate.Add(tms).ToString();
            }
            else
                return "";
        }

asp.net create file from base 64

       public static bool CreateFileFromBase64(string fileName, string Base64Data)
        {
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
                byte[] data = Convert.FromBase64String(Base64Data);
                fs.Write(data, 0, data.Length);
                fs.Close();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }

asp.net create masked value

    public static String CreateMaskedValue(string valueForMask, Int32 numberOfCharacter)
        {
            String maskedString = String.Empty;
            int remainingCharCount = (valueForMask.Length - numberOfCharacter) < 0 ? valueForMask.Length : valueForMask.Length - numberOfCharacter;
            if (remainingCharCount > 0)
            {
                if (!string.IsNullOrEmpty(valueForMask))
                {
                    if (valueForMask.Length > 0)
                    {
                        maskedString = string.Concat("".PadLeft(numberOfCharacter, 'x'), valueForMask.Substring(valueForMask.Length - remainingCharCount));
                    }
                }
                return maskedString;
            }
            else
                return valueForMask;


        }

asp.net telerik convert docx to html

   public static string ConvertDocxToHtml(byte[] binaryData)
        {
            DocxFormatProvider docxProvider = new DocxFormatProvider();
            RadFlowDocument flowDoc = docxProvider.Import(binaryData);

            HtmlFormatProvider htmlProvider = new HtmlFormatProvider();
            string result = htmlProvider.Export(flowDoc);

            return result;
        }

Tuesday, September 22, 2015

asp.net fire button click in javascript function pass parameters

1) Javascript function

 function SetDocumentEditorSrc(WrkID) {
                __doPostBack('<%= btnSetRadEditorContent.UniqueID %>', WrkID);
            }

2)  Button Click Event

        protected void btnSetRadEditorContent_Click(object sender, EventArgs e)
        {
            String fileId = Request["__EVENTARGUMENT"]; // parameter
            if (!String.IsNullOrEmpty(fileId))
            {
                String convertedContent = "";

                RxOffice.BLL.Document document = new RxOffice.BLL.Document();
                document.SetRadEditorContent(Convert.ToInt32(fileId));
                if (!String.IsNullOrEmpty(convertedContent))
                {
                    RadEditor1.Content = convertedContent;
                }
            }

            //string filePath = Server.MapPath("~/SampleInitialContent.docx");
            //byte[] fileBinaryData = File.ReadAllBytes(filePath);
            //string convertedContent = Functions.ConvertDocxToHtml(fileBinaryData);

        }

asp.net update panel

1) Update Panel

<asp:UpdatePanel runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSetRadEditorContent" EventName="Click" />
</Triggers>
<ContentTemplate>
<div style="float: left; width: 59%; margin-left: 10px; border: 1px solid #e2e6eb;">
<%--<iframe id="ifrmWrkDocViewer" src="#" style="height: 430px !important; width: 100%; margin-left: 5px;"></iframe>--%>
<telerik:RadEditor ID="RadEditor1" runat="server" ContentFilters="DefaultFilters, PdfExportFilter">
<ExportSettings FileName="RadEditorExport" OpenInNewWindow="true"></ExportSettings>
</telerik:RadEditor>
<asp:Button ID="btnSetRadEditorContent" runat="server" OnClick="btnSetRadEditorContent_Click" Style="display: none;" />
</div>
</ContentTemplate>
</asp:UpdatePanel>


2) Button click

protected void btnSetRadEditorContent_Click(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/SampleInitialContent.docx");
byte[] fileBinaryData = File.ReadAllBytes(filePath);
string convertedContent = Functions.ConvertDocxToHtml(fileBinaryData);

RadEditor1.Content = convertedContent;
}


3) Javascript Function

 function SetDocumentEditorSrc(WrkID) {
                __doPostBack('<%= btnSetRadEditorContent.UniqueID %>');
            }


asp.net fire button click in javascript function

<asp:Button ID="btnSetRadEditorContent" runat="server" OnClick="btnSetRadEditorContent_Click" Style="display: none;" />


 function SetDocumentEditorSrc(WrkID) {
                __doPostBack('<%= btnSetRadEditorContent.UniqueID %>');
            }


  protected void btnSetRadEditorContent_Click(object sender, EventArgs e)
        {
            string filePath = Server.MapPath("~/SampleInitialContent.docx");
            byte[] fileBinaryData = File.ReadAllBytes(filePath);
            string convertedContent = Functions.ConvertDocxToHtml(fileBinaryData);

            RadEditor1.Content = convertedContent;
        }

Thursday, September 10, 2015

sql conditional insert,update,delete with merge command



declare @target table
(
id int,
lead_id int
)
insert into @target(id,lead_id) values(1,521),(2,521),(1,13),(2,13)
--select * from @target

declare @source table
(
id int,
lead_id int
)

insert into @source(id,lead_id) values(2,521),(3,521),(4,521)
--select * from @source

merge into @target as ttable
using @source as stable
on stable.lead_id = ttable.lead_id and stable.id = ttable.id
when NOT MATCHED then
INSERT (id,lead_id)
VALUES(stable.id,stable.lead_id)
WHEN NOT MATCHED BY SOURCE
AND ttable.lead_id IN(521) THEN
        DELETE;

select * from @target

Tuesday, September 1, 2015

telerik kendo grid refresh after create,update,delete event

 var dataSourceBudgetStatus = new kendo.data.DataSource({
            transport: {
                read: {
                    url: APIbaseUrl + "/Workflow/GetBudgetStatus",
                    dataType: "json",
                    type: "POST",
                    data: budgetStatusInfo
                },
                update: {
                    url: APIbaseUrl + "/Workflow/AddUpdateBudgetStatus",
                    dataType: "json",
                    type: "POST",
                    data: budgetStatusInfo
                },
                destroy: {
                    url: APIbaseUrl + "/Workflow/GetBudgetStatus",
                    dataType: "json",
                    type: "POST",
                    data: budgetStatusInfo
                },
                create: {
                    url: APIbaseUrl + "/Workflow/AddUpdateBudgetStatus",
                    dataType: "json",
                    type: "POST",
                    data: budgetStatusInfo,
                },
                parameterMap: function (options, operation) {

                    if (operation !== "read" && options.models[0]) {
                        options.models[0].ExpenseWorkflowId = 4;//parseInt($('input[id$=hdnExpenseId]').val());
                        return options.models[0];
                    }
                    else if (operation == "read" && options.models) {
                        return options.models;
                    }

                }
            },
            requestEnd: function (e) {
                var type = e.type;
                if (type != "read") {
                    $('#budgetstatusgrid').data('kendoGrid').dataSource.read();
                }
            },
            batch: true,
            pageSize: 5,
            schema: {
                model: {
                    id: "BudgetStatusId",
                    fields: {
                        BudgetStatusId: { editable: false, nullable: true },
                        ExpenseWorkflowId: { editable: false, nullable: true },
                        ExpenseHead: { validation: { required: true } },
                        TotalBudget: { validation: { required: true } },
                        TotalExpenseIncurredTillDate: { validation: { required: true } },
                        CurrentExpenses: { validation: { required: true } },
                        RemainingBudget: { validation: { required: true } }
                    }
                }
            }
        });

Thursday, August 27, 2015

Telerik kendo ui grid - How to pass data from page to api service

<div style="width: 99%; margin-left: 6px; margin-right: 6px;">
                                    <div id="example">
                                        <div id="grid"></div>
                                    </div>
                                </div>





$(document).ready(function () {

            var APIbaseUrl = '<%=this.APIbaseUrl%>';

            var models = {};
            var expenseWorkflowInfo = {
                models: {
                    ExpenseId: 1
                }
            };

            var dataSource = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: APIbaseUrl + "/User/Product",
                        dataType: "json",
                        type: "POST",
                        data: expenseWorkflowInfo
                    },
                    update: {
                        url: APIbaseUrl + "/User/Product",
                        dataType: "json",
                        type: "POST",
                        data: expenseWorkflowInfo
                    },
                    destroy: {
                        url: APIbaseUrl + "/User/Product",
                        dataType: "json",
                        type: "POST",
                        data: expenseWorkflowInfo
                    },
                    create: {
                        url: APIbaseUrl + "/User/Product",
                        dataType: "json",
                        type: "POST",
                        data: expenseWorkflowInfo
                    },
                    parameterMap: function (options, operation) {
                        debugger;
                        if (operation !== "read" && options.models[0]) {
                            return options.models[0];
                        }
                        else if (operation == "read" && options.models) {
                            return options.models;
                        }

                    }
                },
                batch: true,
                pageSize: 5,
                schema: {
                    model: {
                        id: "ExpenseId",
                        fields: {
                            ExpenseId: { editable: false, nullable: true },
                            Subject: { validation: { required: true } }//,
                            //BranchId: { type: "number", validation: { required: true } },
                            //LeadId: { type: "number", validation: { required: true } }
                        }
                    }
                }
            });

            $("#grid").kendoGrid({
                dataSource: dataSource,
                pageable: true,
                height: 550,
                toolbar: ["create"],
                columns: [
                    "Subject",
                    //{ field: "BranchId", title: "Branch Id", format: "{0:c}", width: "120px" },
                    //{ field: "LeadId", title: "Lead Id", width: "120px" },
                    { command: ["edit", "destroy"], title: "&nbsp;", width: "250px" }],
                editable: "inline"
            });

        });

Tuesday, August 18, 2015

Call parent Javascript function from inside an iframe

window.parent.rxTreeSelectNode(folderID);

rxTreeSelectNode - Your Function Name

Iframe set source or href using jquery

    var folderID = $(this).closest('[id]').attr('id');
                var url = 'UploadMultipleFiles.aspx?folderId=' + folderID;
                $('#myframe').attr("src", url);

asp.net access c# variable in javascript

1)  asp.net code behind
 public partial class UploadMultipleFiles : System.Web.UI.Page
    {
        public string eCabinetbaseURL = Functions.ToString(ConfigurationManager.AppSettings["eCabinetServiceUrl"]);

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }

2)  In Javascript function

 var eCabinetServiceUrl = '<%=eCabinetbaseURL%>';


Jquery get session value asp.net

var sessionId = '<%=HttpContext.Current.Session["SessionID"]%>';

jquery get Url parameters

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

Tuesday, August 4, 2015

Could not load file or assembly System.Net.Http.Primitives. Located assembly's manifest definition does not match the assembly reference

Add


 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0" />
</dependentAssembly>
</assemblyBinding>


Remove <assemblyBinding  appliesTo="v.02" attribute

if attribute present it search for system.primitive dll with version 1.5. which is not present
else it loads System.Net.Http.Primitives with 4.2.29.0

Don't touch machine.config because its a heart of system server.
Doctor never opens patient's heart for chest pain.


Wednesday, July 29, 2015

asp.net google drive api service account System.Security.Cryptography.CryptographicException: An internal error occurred

  var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet |
                                     X509KeyStorageFlags.Exportable);

Monday, July 13, 2015

SQL check null in where condition

 where (ISNULL(NULLIF(@tptCode,''),N'') =N'' OR msl.tpt_cd= @tptCode)     

Wednesday, July 8, 2015

SQLHelper code for database connection

using System;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;

namespace Alert
{
    public abstract class SqlHelper
    {
        public static readonly string ConnectionStringLocalTransaction = TrippleDES.Decrypt(ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString);

        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                {
                    if (parm.SqlValue == null) { parm.SqlValue = DBNull.Value; }
                    cmd.Parameters.Add(parm);
                }
            }
        }

        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to
            // close the connection throw code, because no datareader will exist, hence the
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        public static SqlParameter SqlParameter(string paramName, SqlDbType dbType, int Size, object value, bool isDBNullCheck = false, ParameterDirection direction = ParameterDirection.Input)
        {
            System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter(paramName, dbType, Size);
            param.Direction = direction;
            param.Value = value;

            if (isDBNullCheck)
                if (string.IsNullOrEmpty(Convert.ToString(value)))
                {
                    param.Value = DBNull.Value;
                }

            return param;
        }

        public static SqlParameter SqlParameter(string paramName, SqlDbType dbType, object value, bool isDBNullCheck = false, ParameterDirection direction = ParameterDirection.Input)
        {
            System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter(paramName, dbType);
            param.Direction = direction;

            param.Value = value;

            if (isDBNullCheck)
                if (string.IsNullOrEmpty(Convert.ToString(value)))
                {
                    param.Value = DBNull.Value;
                }

            return param;
        }
    }
}

SQL Like query

select login_id,first_name + ' ' + last_name as name,'0' as evuda,count(*) over () as [record_count]
from userinfo
where comp_id = @LoginCompId
and first_name like '%'+ isnull(ltrim(rtrim(@UserName)),first_name) +'%'  
or last_name like '%'+ isnull(ltrim(rtrim(@UserName)),last_name) +'%'

Monday, June 29, 2015

Thursday, June 18, 2015

SQL nested case when then

 CASE
WHEN alertcon.alert_type = 'E'
THEN
CASE
    WHEN alertgat.gateway_id = 'M' THEN escUser.login_id
    WHEN alertgat.gateway_id = 'E' THEN escUser.email_id
    ELSE ''
END
WHEN alertcon.alert_type = 'R'
THEN
CASE
   WHEN alertgat.gateway_id = 'M' THEN escUser.login_id
   WHEN alertgat.gateway_id = 'E' THEN escUser.email_id
    ELSE ''
END
END as Recepient

Monday, June 15, 2015

Static Cursors

A static cursor populates the result set at the time of cursor creation and query result is cached for the lifetime of the cursor. A static cursor can move forward and backward direction. A static cursor is slower and use more memory in comparison to other cursor. Hence you should use it only if scrolling is required and other types of cursors are not suitable.
No UPDATE, INSERT, or DELETE operations are reflected in a static cursor (unless the cursor is closed and reopened). By default static cursors are scrollable. SQL Server static cursors are always read-only.

  1. SET NOCOUNT ON
  2. DECLARE @Id int
  3. DECLARE @name varchar(50)
  4. DECLARE @salary int
  5. DECLARE cur_emp CURSOR
  6. STATIC FOR
  7. SELECT EmpID,EmpName,Salary from Employee
  8. OPEN cur_emp
  9. IF @@CURSOR_ROWS > 0
  10. BEGIN
  11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
  12. WHILE @@Fetch_status = 0
  13. BEGIN
  14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
  15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
  16. END
  17. END
  18. CLOSE cur_emp
  19. DEALLOCATE cur_emp
  20. SET NOCOUNT OFF