Thursday 3 September 2015

Download Word, Pdf Files using Asp.Net

Download Word Document
string sourcefile = Server.MapPath("~/WordDoc/ " + filename + ".doc");
if (File.Exists(sourcefile))
{
System.IO.FileInfo downloadFile = new System.IO.FileInfo(sourcefile);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/odc";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", downloadFile.Name));
HttpContext.Current.Response.AddHeader("Content-Length", downloadFile.Length.ToString());
HttpContext.Current.Response.WriteFile(downloadFile.FullName);
//HttpContext.Current.Response.End();
//HttpContext.Current.Response.Close();
}
 In above example, we are downloading a .doc file.
 Here are some of the most common content types replace in above code:
  •  .htm, .html     Response.ContentType = "text/HTML";
  • .txt    Response.ContentType = "text/plain";
  • .doc, .rtf, .docx    Response.ContentType = "Application/msword";
  • .xls, .xlsx    Response.ContentType = "Application/x-msexcel";
  • .jpg, .jpeg    Response.ContentType = "image/jpeg";
  • .gif    Response.ContentType =  "image/GIF";
  • .pdf    Response.ContentType = "application/pdf";

Monday 24 August 2015

Define Stored Procedure, advantages and when to use ?

Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called.

Purposes and advantages of stored procedures:
  • Manage, control and validate data
  • It can also be used for access mechanisms
  • Large queries can be avoided
  • Reduces network traffic since they need not be recompiled
  • Even though the stored procedure itself may be a complex piece of code, we need not write it over and over again. Hence stored procedures increases reusability of code
  • Permissions can be granted for stored procedures. Hence, increases security.
Determine when to use stored procedure to complete SQL Server tasks.
  • If a large piece of code needs to be performed repeatedly, stored procedures are ideal
  • When hundreds of lines of SQL code need to be sent; it is better to use stored procedure through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.
  • When security is required.


Monday 10 August 2015

Redirect to new asp.net page and javascript alert

Response.Write("<script>alert('Javascript alert message box');</script>");
Response.AddHeader("REFRESH", "3; ./default.aspx);


Javascript alert in asp.net (In another way)

ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Error_msg", "alert('" + ex.Message + "')", true);


SQL Server Tricks

Convert Integer to Decimal

select isnull(format(99,'N'),0) as [integer to decimal]

Convert Decimal  to Integer

select convert(int,150.6,0) as [Decimal to Integer]

Find Recent Created Stored Procedure, Date


SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc


Wednesday 15 July 2015

WCF Errors

The type 'TransactionService.TransactionInfo', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.

I changed the output path of the service. it should be inside bin folder of the service project. Once I put the output path back to bin, it worked.

WCF - Contract Name could not be found in the list of contracts

Your contract is the Interface not the implementation.Somewhere in the config you have written myService instead of IJsonService.

Monday 6 July 2015

Files Upload in FTP Using C#

using System.IO;
using System.Net;

Path = Server.MapPath("~/Folder/file_Name.txt");

private void UploadToFTP(string Path)
    {
        FileInfo fileInfo = new FileInfo(Path);
        string uri = "ftp://000.000.000.00/folder/" + fileInfo.Name;
        FtpWebRequest reqFTP;

        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://000.000.000.00/folder/" + fileInfo.Name));
        reqFTP.Credentials = new NetworkCredential("userName""password");
        reqFTP.KeepAlive = false;
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
        reqFTP.UseBinary = true;
        reqFTP.UsePassive = false;
        reqFTP.ContentLength = fileInfo.Length;
        int buffLength = 10240;
        byte[] buff = new byte[buffLength];
        int contentLen;
        FileStream fs = fileInfo.OpenRead();
        try
        {
            Stream strm = reqFTP.GetRequestStream();
            contentLen = fs.Read(buff, 0, buffLength);
            while (contentLen != 0)
            {
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }
            strm.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }

    }


Send Mail with Attachment Files Using Asp.net

using System.Net.Mail;

SmtpClient client = new SmtpClient();
            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            client.Timeout = 10000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "Password");

            MailMessage mm = new MailMessage();
            mm.Subject = "Sending Mail Using Asp.net";
            mm.Body = "Hi, \n\n\Mail Sent Successfully \n\n\n --\n -- \nBest Regards\n"
                + "\n\n-----------------------------------------------------------------------\nThis is a system-generated e-mail, please don't reply to this message.";
            mm.Attachments.Add(new Attachment(File));
            mm.From = new MailAddress("xyz@gmail.com");
            mm.To.Add("xyz@gmail.com");             
            mm.CC.Add("xyz@gmail.com");
            client.Send(mm);

Saturday 4 July 2015

Print Gridview using JavaScript

<script  type="text/javascript">
        function CallPrint(strid) {
            var prtContent = document.getElementById(strid);
            var WinPrint = window.open('', '', 'letf=0,top=0,width=900,height=600,toolbar=1,scrollbars=1,status=1');
            WinPrint.document.write(prtContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            prtContent.innerHTML = strOldOne;
            WinPrint.close();
        }

    </script>

<input id="btnPrint" onclick="javascript: CallPrint('divPrint')" type="button" value="Print" visible="True" />

<div id="divPrint" align="center">
            <asp:GridView ID="GridView2" runat="server"></asp:GridView>
</div>

Wednesday 1 July 2015

Dot Net Tricks

Showing number in 2 decimal places in gridview

Using DataFormatString="{0:0.00}" we can do


<asp:BoundField DataField="Number" HeaderText="Number with 2 decimal" ReadOnly="True" DataFormatString="{0:0.00}" SortExpression="Number">

Tuesday 30 June 2015

Exceptions in DotNet

control gridview of type 'gridview' must be placed inside a form tag with runat=server

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}


IFSC Code Validation using JavaScript in Asp.net

function AllowIFSC() {
            var ifsc = document.getElementById('<%=txtifsccode.ClientID%>').value;
            var reg = /[A-Z|a-z]{4}[0][a-zA-Z0-9]{6}$/;

            if (ifsc.match(reg)) {
                return true;
            }
            else {
                alert("You Entered Wrong IFSC Code \n\n ------ or------ \n\n IFSC code should be count 11 \n\n-> Starting 4 should be only alphabets[A-Z] \n\n-> Remaining 7 should be accepting only alphanumeric");
                document.getElementById("<%=txtifsccode.ClientID%>").focus();
                return false;
            }

        }

<asp:TextBox ID="txtifsccode" runat="server" onblur="return AllowIFSC();"  MaxLength="11" Width="200" Style='text-transform: uppercase'></asp:TextBox>