Monday, December 10, 2012

How to create PROXY CLASS from WebSerivce

Open Visual Studio Command Prompt and run below

wsdl /out:myProxyClass.cs http://hostserver/application/service.asmx?WSDL

It will create a C# class in C Drive

Thursday, November 1, 2012

HOW TO KNOW SQL QUERY EXECUTION TIME


--Track query execution time
DECLARE @EndTime   DATETIME
DECLARE @StartTime DATETIME
SET @StartTime = GETDATE()

--Query goes here
select * from My_Table

SET @EndTime = GETDATE()

PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
PRINT ' Duration = ' + convert(varchar,DATEDIFF(ms, @StartTime, @EndTime))+' mill seconds'

Wednesday, October 3, 2012

GET GIVEN DATE FORMAT FOR GIVEN INPUT FORMAT


private string DateFormat(string DateValue, string DateFormat, string RequiredFormat)
        {
            string result = DateValue;
            IFormatProvider provider = CultureInfo.InvariantCulture;
            try
            {
                if (!string.IsNullOrEmpty(DateValue) && !string.IsNullOrEmpty(DateFormat))
                    result = DateTime.ParseExact(DateValue, DateFormat, provider).ToString(RequiredFormat);

            }
            catch (Exception ex)
            {              
                throw ex;
            }
            return result;
        }

Monday, September 17, 2012

SELECT TRIGGERS LIST IN A DATABASE IN SQL SERVER


SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects

INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid

INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

WHERE sysobjects.type = 'TR'

Wednesday, September 5, 2012

HOW TO CONVERT FIRST LETTER OF EACH WORD TO UPPER CASE USING C#


 public string UPPERCASE_FIRSTCHAR(string source)
        {
            string result = "";
            try
            {
                result = source;
                if (!string.IsNullOrEmpty(source))                  
                source=System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(source.ToLower());
            }
            catch (Exception ex)
            {
               throw ex;
            }
            return source;
        }

Thursday, August 23, 2012

Execute Batch File Using c#.net


   private void ExecuteBatch(string strFilePath)
        {
            string fullPath = Directory.GetParent(strFilePath).FullName;
            // Create the ProcessInfo object
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = fullPath;// strPath;

            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
            // Open the batch file for reading
            System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
            // Attach the output for reading
            System.IO.StreamReader sOut = proc.StandardOutput;
            // Attach the in for writing
            System.IO.StreamWriter sIn = proc.StandardInput;
            // Write each line of the batch file to standard input
            while (strm.Peek() != -1)
            {
                sIn.WriteLine(strm.ReadLine());
            }
            strm.Close();
            // Exit CMD.EXE
            string stEchoFmt = "# {0} run successfully. Exiting";
            sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
            sIn.WriteLine("EXIT");
            // Close the process
            proc.Close();
            //this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
            sIn.Close();
            sOut.Close();
        }

Tuesday, August 21, 2012

GridView Javascript Validations


GridView needs 2 types of validations as below:

1. FooterRow Validations while Adding
2.EditRow Validations while updating

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Footer Row Validations.
In the below code, GridViewID is gridview id. replace textbox id as per requirment.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 <script type="text/javascript">
function Validate_Add() {
        var error = "";
        var code = document.getElementById('<%=((TextBox)GridViewID.FooterRow.FindControl("txtAddCode")).ClientID%>')
        var Server = document.getElementById('<%=((TextBox)GridViewID.FooterRow.FindControl("txtAddServerName")).ClientID%>')
        var username = document.getElementById('<%=((TextBox)GridViewID.FooterRow.FindControl("txtAddUserName")).ClientID%>')
        var password = document.getElementById('<%=((TextBox)GridViewID.FooterRow.FindControl("txtAddServerPassword")).ClientID%>')
        if(code=="")
        error+="Enter Unique Code for  Server";
        if (Server.value == "") {
            error += "Enter  Server Name\r\n";          
        }    
        if (username.value == "")
            error += "Enter  Server User Name\r\n";
        if (password.value == "")
            error += "Enter  Server User Password\r\n";

        if (error == "")
            return true;
        else {
            alert(error)
            return false;
            }
        }



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Edit Row Validations.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        function Validate_Edit(btnCtrl) {
            var error = "";
            var selectedRowIndex = btnCtrl.parentNode.parentNode.rowIndex;
            var gridView = document.getElementById('<%= GridViewID.ClientID %>');

            var Server = gridView.rows[parseInt(selectedRowIndex)].cells[1].children[0];
            var user_name = gridView.rows[parseInt(selectedRowIndex)].cells[2].children[0];
            var password = gridView.rows[parseInt(selectedRowIndex)].cells[3].children[0];
            if (Server.value == "")
                error += "Enter  Server Name\r\n";
            if (user_name.value == "")
                error += "Enter  User Name\r\n";
            if (password.value == "")
                error += "Enter  Server User Password\r\n";

            if (error == "")
                return true;
            else {
                alert(error)
                return false;
            }
        }
   
    </script>


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GridView Code
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


<asp:GridView ID="GridViewID" runat="server" CssClass="GridStyle" HorizontalAlign="Left"
            AutoGenerateColumns="false" DataKeyNames="Code" AllowPaging="True" PageSize="10"
            ShowFooter="true" OnRowCancelingEdit="GridViewID_RowCancelingEdit" OnRowCommand="GridViewID_RowCommand"
            OnRowDeleting="GridViewID_RowDeleting" OnRowEditing="GridViewID_RowEditing"
            OnRowUpdating="GridViewID_RowUpdating">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        Code</HeaderTemplate>
                    <ItemTemplate>
                        <%#Eval("Code") %></ItemTemplate>
                    <EditItemTemplate>
                        <%#Eval("Code") %>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddCode" runat="server" CssClass="gridcontrol" MaxLength="10"
                            ToolTip="EnterUnique code for  Server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        Server Name</HeaderTemplate>
                    <ItemTemplate>
                        <%#Eval("ServerName") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditServerName" runat="server" CssClass="gridcontrol" Text='<%#Eval("ServerName") %>'
                            MaxLength="100" ToolTip="Enter  Server Name"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddServerName" runat="server" CssClass="gridcontrol" MaxLength="100"
                            ToolTip="Enter  Server Name"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        User Name</HeaderTemplate>
                    <ItemTemplate>
                        <%#Eval("UserName") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditUserName" runat="server" CssClass="gridcontrol" Text='<%#Eval("UserName") %>'
                            MaxLength="100" ToolTip="Enter  Server User Name"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddUserName" runat="server" CssClass="gridcontrol" MaxLength="100"
                            ToolTip="Enter  Server User Name"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        Password</HeaderTemplate>
                    <ItemTemplate>
                        ******</ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditPassword" runat="server" CssClass="gridcontrol" TextMode="Password"
                            MaxLength="100" ToolTip="Enter  Server User Passwor"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddServerPassword" runat="server" CssClass="gridcontrol" TextMode="Password"
                            MaxLength="100" ToolTip="Enter  Server User Passwor"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        Description</HeaderTemplate>
                    <ItemTemplate>
                        <%#Eval("Desc") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditDesc" runat="server" CssClass="gridcontrol" MaxLength="100"
                            Text='<%#Eval("Desc") %>' ToolTip="Enter Description"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddDesc" runat="server" CssClass="gridcontrol" MaxLength="100"
                            ToolTip="Enter Description"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/Edit.png"
                            ToolTip="Edit this  Server" CssClass="iconstyle" />
                        <asp:ImageButton ID="imgDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/delete.png"
                            ToolTip="Delete this  Server" CssClass="iconstyle" OnClientClick="javascript:return confirm('Are you sure you want to Delete this  Server ?','Yes','No');" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:ImageButton ID="imgUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/Update.png"
                            ToolTip="Update this  Server" CssClass="iconstyle" OnClientClick="return Validate_Edit(this)" />
                        <asp:ImageButton ID="imgDelete" runat="server" CommandName="Cancel" ImageUrl="~/Images/Cancel.png"
                            ToolTip="Cancel Editing of this  Server" CssClass="iconstyle" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btnAdd" CssClass="btnstyle" ToolTip="Add  Server" CommandName="Add"
                            runat="server" Text="Add" OnClientClick="return Validate_Add();" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>          
            <FooterStyle CssClass="GridFooter" />
            <HeaderStyle CssClass="GridHeader" />
            <PagerSettings Mode="NumericFirstLast" />
            <PagerStyle HorizontalAlign="Center" CssClass="GridPager" />
            <AlternatingRowStyle CssClass="GridAlter" />
            <RowStyle CssClass="GridRowStyle" />
        </asp:GridView>



Sunday, August 19, 2012

save text into notepad using c#.net

 public static void SaveMessage(string Message,string FileName)
        {
            string path = HttpContext.Current.Server.MapPath("Messages");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string filename = path + "\\" +FileName+"_"+ DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + ".txt";
            string error = "\r\nMessage Occur at :" + DateTime.Now.ToString() +
              "\r\nMessage is : \r\n" + Message +          
              "\r\n***********************************************************************************************************************";
            using (StreamWriter strwr = File.AppendText(path))
            {
                strwr.WriteLine(error);
                strwr.Flush();
                strwr.Close();
            }
        }

DATE VALIDATION USING JAVASCRIPT

function isValidDate(sText) {
04          var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{4})/;
05         return reDate.test(sText);
06        }

Friday, August 17, 2012

how to put icon in browser url for Web Applications

Create image with 30X30 pixels size and save it as .png.

Open below website.

http://www.convertico.com/

browse the created image and click on GO,
Download the generate .ico file in the same page.

Copy the .ico image and paste in your web application and give add below code in the page header

<link rel="SHORTCUT ICON" href="<%=ResolveClientUrl("~")%>Images/icon.ico"/>

in the above example, icon.ico is image name located in Images folder.

For ASP.NET applications, put the above code in master pages so that it will apply for all its content pages.

Wednesday, July 25, 2012

Detach and Attach MSSQL DB



-- Get the datafiles location for the DB which you want to move
use MY_DATABASE
go
sp_helpfile
go

-- Deatch the DB which you want to move
use master
go
sp_detach_db 'MY_DATABASE'
go

-- Copy the files listed from step1 to new destination directory

-- Attach the DB with new files location
use master
go
sp_attach_db 'MY_DATABASE','D:\MSSQL\DATA\MY_DATABASE.mdf','D:\MSSQL\DATA\MY_DATABASE_1.ndf','D:\MSSQL\DATA\MY_DATABASE_2.ldf'
go


-- Get the New datafiles location for the DB which you moved
use MY_DATABASE
go
sp_helpfile
go


--For More Help, use below link
--http://support.microsoft.com/kb/224071

Tuesday, July 17, 2012

II6 compatability with II7


Issues Faced with Installer

Error message: 


at least knew how to start the msi package in verbose mode to create the log files.
Launch your msi in verbose mode:
msiexec /i yoursetup.msi /lv "C:\yourdirectory\logfile.txt"

msiexec /i C:\PaperlessRelease\PaperlessWSSetup.msi /lv "C:\PaperlessRelease\logfile.txt"
How to install the IIS 6 Metabase Compatibility components on IIS 7
The ActiveXperts Network Monitor Web Configurator requires that the Windows Server 2008-based or Windows Vista-based computer where you are configuring a Virtual Directory has the IIS 6 Metabase Compatibility components installed.
To install the IIS 6.0 Management Compatibility Components by using the Windows Server 2008 Server Manager
  • Click Start, click Administrative Tools and then Server Manager.
  • In the left navigation pane, expand Roles, and then right-click Web Server (IIS) and select Add Role Services.
  • On the Select Role Services pane, scroll down to IIS 6 Management Compatibility.
  • Select the check boxes for IIS 6 Metabase Compatibility and IIS 6 Management Console.
  • Click Next from the Select Role Services pane, and then click Install at the Confirm Installations Selections pane.
  • Click Close to leave the Add Role Services wizard.
To install the IIS 6.0 Management Compatibility Components by using the Windows Vista Control Panel
  • Click Start, click Control Panel, click Programs and Features, and then click Turn Windows features on or off.
  • Open Internet Information Services.
  • Open Web Management Tools.
  • Open IIS 6.0 Management Compatibility.
  • Select the check boxes for IIS 6 Metabase and IIS 6 configuration compatibility and IIS 6 Management Console.
  • Click OK.
To install the IIS 6.0 Management Compatibility Components by using the Windows 7 Control Panel
If you deploy a Web Forms application to a remote server running IIS 7, or if you publish a smart client application to a local or remote server running IIS 7, the Vista Metabase Compatibility component of IIS 7 must be installed on the server. This component is not installed by default. It is not required to deploy a Web Forms application to a local server.
You can install it from the Programs and Features page in the Windows control panel. Select Turn Windows features on or off, then select Internet Information Services>Web Management Tools>IIS 6 Management Compatibility>IIS Metabase and IIS 6 configuration compatibility.



Issue – 3
“HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by the static file handler. "
Solution 
 cmd As Administrator -> cd C:\Windows\Microsoft.NET\Framework64\v2.0.30319 ->aspnet_regiis -i

Friday, April 20, 2012

How to call a method using Reflection in C#.net


public static object Reflection_Result(string Method, string DllName, string ClassName, object[] ParametersList)
        {
            object result;
            try
            {
                DllName = DllName.Replace(".dll", "");
                string dll = Path.GetFileName(DllName);

                Assembly assembly = Assembly.LoadFrom(DllName + ".dll");
                object obj1 = assembly.CreateInstance(dll + "." + ClassName);
                Type type1 = obj1.GetType();
                result = type1.GetMethod(Method).Invoke(obj1, ParametersList);
            }
            catch (Exception ex)
            {
                ErrorLogs.SaveError(ex, "COMMON_UTILITY");
                throw ex;
            }
            return result;
        }

Wednesday, April 11, 2012

Create XML File using C#.NET

public void Create_DB_XML(string TenantName,string ServerName,string DatabaseName,string UserName,string Password)

{

string filename = "C\\DataBaseDetails.xml";

if (File.Exists(filename))

File.Delete(filename);

XmlWriterSettings settings = new XmlWriterSettings();

settings.OmitXmlDeclaration = true;

settings.ConformanceLevel = ConformanceLevel.Fragment;

settings.CloseOutput = false;

StringBuilder sb = new StringBuilder();

XmlWriter writer = XmlWriter.Create(sb, settings);

writer.WriteStartElement("Databases", "");

writer.WriteStartElement("DB", "");

writer.WriteAttributeString("TenentId", TenantName);

writer.WriteElementString("userid", UserName);

writer.WriteElementString("password", Password);

writer.WriteElementString("database", DatabaseName);

writer.WriteElementString("server", ServerName);

writer.WriteEndElement();

writer.WriteEndElement();

writer.Flush();

writer.Close();

string ss = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";

ss = ss + sb.ToString();

StringReader stream = new StringReader(ss);

XmlTextReader reader = new XmlTextReader(stream);

XmlDocument dom = new XmlDocument();

dom.Load(reader);

dom.Save(filename);

}




|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
OutPut
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

<?
xml version="1.0" encoding="utf-8"?>

<Databases>

<DB TenentId="hosp">

<userid>uuuuuu</userid>

<password>pppppp</password>

<database>ddddddd</database>

<server>sssssssss</server>

</DB>

</Databases>

Friday, January 6, 2012

How to call Javascript code using Asp.Net


In the below code, Pop_close() is a javascript method.

 //string script = "<script language='javascript'> ";
                 //script += "popup_close();";
                 //script += "</script>";
                 //Page.RegisterClientScriptBlock("ClientScript", script);