Tuesday, November 15, 2011

Position cursor after all contents in Asp.Net TextBox

<asp:TextBox ID="TextBox1" runat="server"
onfocus="FocusAtLast();"
 ></asp:TextBox>

    function FocusAtLast () {
       
    var inputField = document.getElementById('<%= TextBox1.ClientID %>');
    if (inputField != null && inputField.value.length> 0)
    {
    if (inputField.createTextRange)
    {
    var FieldRange = inputField.createTextRange();
    FieldRange.moveStart('character',inputField.value.length);
    FieldRange.collapse();
    FieldRange.select();
    }
    }
    }

Reference:

http://msdn.microsoft.com/en-us/library/ms535872%28v=VS.85%29.aspx

Wednesday, November 9, 2011

Sorting in Datatable using C#


DataTable dt = dt.Select("[anycondition]", "[column] desc", DataViewRowState.CurrentRows).CopyToDataTable();

Tuesday, November 8, 2011

Export Tree view into excel without using COM Objects


This code is used to export all tree nodes from telerik tree view. we can also implement to normal tree view.

Tuesday, November 1, 2011

DIV drag drop in JQuery

I come across one scenario that I need to create a pop up which should be draggable.
So I created one popup using JQuery.

Important thing is that i am using update panel in my page. i assigned one css class at design time.
my need is pop up should always open at top of page. if i drag and drop div at page bottom and close the div means , next it is opening only at bottom.

So in order to solve this problem i assign all css properties at run time in javascript on particular control on click event.

you can download jquery files from following links

http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js

Please add script references inside form tag.


Page Design:


function OpenPopup() {
var object = document.getElementById("makeMeDraggable");
object.style.display = "block";
object.style.borderWidth = "2px";
object.style.borderCollapse = "collapse";
object.style.borderStyle = "solid";
object.style.borderColor = "black";
object.style.zIndex = "71";
object.style.position = "fixed";
object.style.width = "75%";
object.style.top = "10px";
object.style.left = "10%";
object.style.cursor = "move";
object.style.backgroundColor = "Red";
}


<form id="form1" runat="server">
<script src="../Scripts/jquery.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(init); function init()
{ $('#makeMeDraggable').draggable(); }
</script>
<a onclick="OpenPopup();">Click here</a>
   
<div id="makeMeDraggable" style="display: none">
<div>
//Add your design here
// add any controls like grid to load dynamic data
</div>
</div>
</form>

Monday, October 31, 2011

Invoking Controls and function in page and iframes in javascript

How to access child window from parent window?

We can access the child window elements by using the window handle that will be returned by the window.open() method, as shown below:
winobj=window.open(..)
...
winobj.document.getElementById("elementname").value=""

The winobj is actually a window object instance of the newly created window


How to access parent window from child window ?
window.opener.document.getElementById('text1').value="Value changed.." ;
window.opener.location.reload

How to call parent page from iframe?

Window.parent.functionName();
window.parent.document.getElementId(...);

var winobj=window.open(..); // this is for opening new child window
winobj.document.getElementById("elementname").value="";

How to call iframe function from parent page?
Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction():
document.getElementById('targetFrame').contentWindow.targetFunction();
You can also access the frame using window.frames instead of document.getElementById.

or

window.frames.iframeName.functionName();


How to call parent page from user control?

To access function inside parent page

Window.parent.functionName();
To access controls inside parent page

window.parent.document.getElementId(...);

How to open new window inside user control?


ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "windowopen", "window.open('www.google.com', 'newwin');", true);

How to restrict accidential navigation from entry page?(On Before Unload in JavaScript)

One of common scenario is that , if we are entering huge data or important data in particular aspx page there may be a chance that accidentally we click on something which causes to navigate another page. so certainly we will lose entered data. To avoid this we must implement, some concepts. one of the helping concept is explained below.

This must be remedied in some way, if you are creating an application that needs the user to input stuff, especially lengthy articles. One approach is to automate draft saving every a few minutes, the other is to warn the user before he or she either intentionally or inadvertently navigate away from the editor page. You can achieve this by a straightforward snippet of JavaScript:
var warning = false;
window.onbeforeunload = function() {
  if (warning) {
    return 'You have unsaved changes.';
  }
}
The warning variable can be timely altered according to the editing activities by the user. For instance, it is set true if the editing field is changed or does not equal to default value, or if the user triggers the onKeyUp / onChange event of any input fields:
var editor_form = document.getElementById("form_id");
for (var i = 0; i < editor_form.length; i++) {
        editor_form[i].onchange = function() {
               warning = true;
        }
}
This snippet must be put at the end of the page. Also, to avoid the warning when you press the form submit button, add this snippet after that:
document.getElementById("submit_button_id").onclick = function() {
    warning = false;
}

Better avoid anchor tag or link button in the page unless it is important.


Friday, October 14, 2011

In MDI forms with out creating new instance of child form how to use already open instance of form?

Tips in MDI forms (Windows application):
========================================
In MDI windows application we will face problem while opening same window again and again.

with out creating new instance of child form how to use already open instance of form?

Form1 objForm1=(Form1) Application.OpenForms["Form1"];

How to create common Data access layer for all database?(DB Provider factory)

Providers factory provides us indepandent database access where we can connect to any database sources(SQLServer,DB2,Oracle,MS-Access).
Provider Factory allows programmers to write their own implementation for accessing database.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
namespace DatabaseProvider
{
   /// <summary>
   ///
   /// Design Pattern: Factory.
   /// </summary>
   public abstract class Database
   {
       private string connectionString;        
       private DbProviderFactory dbProviderFactory;
       private string schema;
       private string dataProvider;
       private bool status;

       protected Database() { }    

       public DbProviderFactory DbProviderFactory
       {
           get { return dbProviderFactory; }
       }      
       public string ConnectionString
       {
           get { return connectionString; }
           set { connectionString = value; }
       }        
       public string Schema
       {
           get { return schema; }
       }

       public string DataProvider
       {
           get { return dataProvider; }
       }
           
       public DbConnection GetConnection()
       {
           DbConnection newConnection = null;
           try
           {
               try
               {
                      ProviderFactory = DbProviderFactories.GetFactory(this.ProviderType);
                      dbConnection = ProviderFactory.CreateConnection();
                      dbConnection.ConnectionString = this.ConnectionString;                    
               }
               catch
               {
                   throw;
               }
           }
           catch
           {
               if (newConnection != null)
                   newConnection.Close();

               throw;
           }

           return newConnection;
       }

       public DbCommand CreateCommand()
       {
           return dbProviderFactory.CreateCommand();
       }

       public DbCommand CreateCommand(string sQueryString, DbConnection connection)
       {
           try
           {
               // Create the DbCommand.
               DbCommand command = this.CreateCommand();
               command.CommandText = sQueryString;
               command.Connection = connection;

               return command;
           }
           catch
           {
               throw;
           }
       }      

       public DbDataAdapter CreateDataAdapter()
       {
           return dbProviderFactory.CreateDataAdapter();
       }
       public DbDataAdapter CreateDataAdapter(string sQueryString, DbConnection connection)
       {
           try
           {
               // Create the DbCommand.
               DbCommand command = this.CreateCommand();
               command.CommandText = sQueryString;
               command.Connection = connection;

               // Create the DbDataAdapter.
               DbDataAdapter adapter = this.CreateDataAdapter();
               adapter.SelectCommand = command;
               
               return adapter;
           }
           catch
           {
               throw;
           }
       }

       private DbCommandBuilder CreateCommandBuilder()
       {
           return dbProviderFactory.CreateCommandBuilder();
       }

       public DbCommandBuilder CreateCommandBuilder(DbDataAdapter dbDA)
       {
           DbCommandBuilder dbCB = this.CreateCommandBuilder();
           dbCB.DataAdapter = dbDA;

           return dbCB;
       }        
   }
}

web.config
<add key="Connectionstring" value="database=local;user id=sa;pwd=sa;initial catalog=northwind"/>
<add key="SQLProvider" value="System.Data.SqlClient"/>
<add key="OledbProvider" value="System.Data.OleDb"/>
<add key="Db2Provider" value="IBM.Data.DB2"/>
<add key="OracleProvider" value="System.Data.OracleClient"/>

aspx.cs
private Database DB;
private DbDataAdapter SQLDA;
private DbCommandBuilder SQLDB;
private DbConnection Conn;
private DBCommand cmd;

//pass the connection string and provider type to create database connection
DB.Connectionstring=Configuration.ConfigurationManager.AppSettings["Connectionstring"].ToString();
DB.DataProvider=Configuration.ConfigurationManager.AppSettings["SQLProvider"].ToString();

//create database connection
Conn = DB.GetConnection();
Conn.Open();

//creating Data Adapter
SQLDA=DB.CreateDataAdapter("select * from emp",Conn);

//Create Command Builder
SQLDB=DB.CreateCommandBuilder(SQLDA);

//Create Command
cmd=DB.CreateCommand("select * from emp",Conn);

Problem in crystal report running at Production server in asp.net ?

<system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <remove name="ScriptModule"/>
            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </modules>
        <handlers>
            <add name="Reserved.ReportViewerWebControl.axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler,  Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="Unspecified" preCondition="integratedMode"/>
            <add verb="*" name="UploadAttachments" path="UploadAttachments.axd" type="UploadAttachments, MAXIDAPP"/>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <remove name="ScriptHandlerFactory"/>
            <remove name="ScriptHandlerFactoryAppServices"/>
            <remove name="ScriptResource"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </handlers>
    </system.webServer>


In windows application, how to access control running in one thread from another thread?


Function Call:
=============

SetControlPropertyValue(lblFail, "Text", "File doesn't exist");
SetControlPropertyValue(lblFail, "Visible", "true");
               

Function definition:
====================
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
       private void SetControlPropertyValue(Control oControl, string propName, object propValue)
       {
           
           if (oControl.InvokeRequired)
           {
               SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
               if (option == 1) //  enable property
               {
                  oControl.Invoke(d, new object[] { oControl, propName, Convert.ToBoolean(propValue) });
               }
             
               else
               {
                   oControl.Invoke(d, new object[] { oControl, propName, propValue });
               }
           }
           else
           {
               Type t = oControl.GetType();
               PropertyInfo[] props = t.GetProperties();
               foreach (PropertyInfo p in props)
               {
                   if (p.Name.ToUpper() == propName.ToUpper())
                   {
                       if (option == 1) //  enable property
                       {
                           p.SetValue(oControl, Convert.ToBoolean(propValue), null);
                      }
                       
                       else
                       {

                           p.SetValue(oControl, propValue, null);
                       }
                       
                   }
                   
               }
           }
       }

URL rewriting in Asp.net

public class Global : System.Web.HttpApplication
   {

       void Application_Start(object sender, EventArgs e)
       {
           // Code that runs on application startup
           RegisterRoutes(RouteTable.Routes);

       }
       void RegisterRoutes(RouteCollection routes)
       {
           routes.MapPageRoute("", "home", "~/home.aspx");
           routes.MapPageRoute("", "vetri/profile/{userid}", "~/vetri/profile.aspx");
       }
}

Access Parent page event from user control event (Custom events)

Create custom Event

Scenario is :

I have user control like just to upload files to server and it returns uploaded file names and path in data table.
i have grid in aspx page to load uploaded files with name.

so i created sample user control.  To use this user control to many aspx pages i found solution to create custom events then passing result data table as argument .

By simply registering and accessing the user control event inside any aspx page we can get result data.

It avoids storing values in session or view state or in any global variable.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace CustomEvents
{
    public class CustomEvents:EventArgs
    {
        object _dt ;

        public CustomEvents(object dtInput)
        {
            _dt = dtInput;

        }
        public object ResultData
        {
            get { return _dt; }
        }
    }
}
--------------------------------------------------------------------------
User control Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace CustomEvents
{
    public partial class ucSample : System.Web.UI.UserControl
    {
        public delegate void CustomDelegate(object sender, CustomEvents e);
        public event CustomDelegate MyCustomEvent;

        protected void Page_Load(object sender, EventArgs e)
        {
        
          
        }

       
        protected void LoadData(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Sample");

            DataRow dr = dt.NewRow();
            dr[0] = "vetrivemp Testing";
            dt.Rows.Add(dr);

            // accessing parent page property
            _Default obj = (_Default)this.Page;
            obj.MyProperty = 456;

            CustomEvents objCustomEvents = new CustomEvents(dt);
                      
            //Event calling in the parent page via delegates
            MyCustomEvent(this, objCustomEvents);
           
        }


    }
}

-----------------------------------------------
Aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CustomEvents._Default" %>
<%@ Register Src="~/ucSample.ascx" TagName="Uc" TagPrefix="Uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <style type="text/css">
    .rsContentTable
    {
    height:100px;
   
   
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
    <asp:GridView ID="gvSample" runat="server" AutoGenerateColumns="true">
   
    </asp:GridView>
   
    <Uc:Uc ID="ucSample" runat="server" OnMyCustomEvent="LoadGridDataCodeBehind" ></Uc:Uc>
   
    </div>
    </form>
</body>
</html>
-------------------------------------------------------------
Aspx code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomEvents
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void LoadGridDataCodeBehind(object sender, CustomEvents e)
        {
            int a = MyProperty;
            gvSample.DataSource = e.ResultData;
            gvSample.DataBind();

        }

        public int MyProperty { get; set; }
    }
}

Asp.net Performance Improvement

http://msdn.microsoft.com/en-us/library/ff647787.aspx#scalenetchapt06_topic15
http://www.sitepoint.com/aspnet-performance-tips/

Cache (.css, .js files) in asp.net using Web.config

    <system.webServer>
    <staticContent>
      <clientCache cacheControlMaxAge="365.00:00:00" cacheControlMode="UseMaxAge" />     
    </staticContent>
 </system.webServer>

Refer link:

http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache

Web.config Encryption and Decryption

For aspnet_regiis
-----------------------------------------------------
C:\Windows\Microsoft.NET\Framework\v4.0.30319
~\Microsoft.NET\Framework\v4.0.30319

Encryption
-------------------------------------------------------------------
aspnet_regiis -pef "appSettings" "D:\Anyfolder\project.Web" -prov "DataProtectionConfigurationProvider"

Decryption
-------------------------------------------------------------------
aspnet_regiis -pdf "appSettings" "D:\Anyfolder\project.Web"

Removing Duplicate Rows in data table using c#

To find distinct records based column or columns, i have found this is the simplest way.

string[] columns=new string[dtTable .Columns.Count];
       int i=0;
       foreach (DataColumn dc in dtTable.Columns)
       {
           columns[i++] = dc.ColumnName.Trim();
       
       }
       
       dtTable = dtTable.DefaultView.ToTable(true, columns);
       return dtTable;

How to store string values in Enum using c#


Could not establish trust relationship for the SSL/TLS secure channel


Default Re: Could not establish trust relationship for the SSL/TLS secure channel.

    Hello,
    the certificate of the server is invalid or not trusted.
    You can either add the root certificate of the server to the trusted root
    certificate store, or use this code to override the check of the .NET
    Framework:

    ..NET 2.0:

    ServicePointManager.ServerCertificateValidationCallback = delegate { return
    true; };

    ..NET 1.1:

    Implement the ICertificatePolicy interface (See MSDN for an example)

Excel impersonate permission in server


All programs=> administrative tools => component services = > dcom config => microsoft excel applications => properties

Add the impersonate account in security tab.  

WCF Important Tips


To Test WCF service  
 
 wcftestclient.exe [C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE] 

To Configure WCF

Configuration Editor Tool (SvcConfigEditor.exe) [C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SvcConfigEditor.exe ]


To Trace WCF Request in server inside <configuration> tag in web.config

 Service Trace Viewer Tool (SvcTraceViewer.exe) [ <Installation_Drive>\Program Files\Microsoft SDKs\Windows\v6.0\Bin ] or [C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin]
  or
open visual studio (web application or web site) => Tools => WCF service configuration editor

To Trace and save service request in server

 <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Verbose,Information, ActivityTracing,Critical,Error,Warning"
              propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

To increase incoming message size in server using web.config