Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, August 17, 2010

Asynchronous File Upload in Asp.net using C# jquery Uploadify

Hello Readers,
You might have a need for uploading files asynchronously in asp.net using c# with jquery.
here i will give u the best tutorial to do this.
You will need to download the jquery pluggin this.download this pluggin from here.
http://www.uploadify.com/download/
after u download this file extract this folder and rename it to uploadify and put it in the root folder of ur project.
Now crate new aspx page from which we will upload file. name it ImageUploader.aspx(you can give any name)
insert the following code in ur header part of ur file.


    

    

    

//reference of css file of uploadify, you will find this in the folder  uploadify
and then in the body of ur page insert the following code...

   
Now let's create the handler to receive the httpPostedData.
Add Generic Handler to ur project(Right click on project from solution explorer and then click on add new item.from the given option select Generic Handler). Name it Uploader.ashx
The code for the handler is as below.
using System;
using System.Web;
using System.Web.SessionState;

public class Uploader : IHttpHandler, IRequiresSessionState
{
    
    public void ProcessRequest (HttpContext context) {
        try
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            int id = (Int32.Parse(context.Request["id"]));//here we are accessing the passed values from the javascript
            string filename = id.ToString() + file.FileName;
            string filepath = HttpContext.Current.Server.MapPath("~").ToString() + "\\Avatar\\"+filename ;
            file.SaveAs(filepath);
            //your asp.net logic to save file path in database
            context.Response.Write("1");
        }
        catch (Exception ex)
        {
            context.Response.Write("0");
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

} 
It's done just run ur imageupload.aspx page and click on browse button to upload the file.
if u face any problem feel free to contact me on
info@amitech.co
Amit Panchal
www.amitech.co

Saturday, August 7, 2010

Running specific JavaScript after partial postback (update panel)

It is very easy to register a new javascript after postback, but if u are using a update panel and want to register a new javascript after a partial postback then you must use the different way then u use in first case.
Here is the code to solve that issue.
i have got this code from the site http://fooberry.com/2009/05/25/running-specific-javascript-after-partial-postback/
here we will create a reusable control so u can use it anywhere u want in ur project.
you can download the code from here.
Download
add this files into ur project.
and now see the code below to use it.
filename.aspx
add the following line in file before head
<%@ Register src="DoAfterPostback.ascx" tagname="DoAfterPostback" tagprefix="uc1" %>
now add the javascript code

    
and web controls as follows:

                
                    
                    
                    
                        Text    ="Button"
                        OnClick ="ButtonClicked" />

                    
                        Text    ="Label" />
                
            
  

filename.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void ButtonClicked(object sender, EventArgs e)
    {
        var s = TextBox1.Text;
        if (string.IsNullOrEmpty(s)) return;

        Label1.Text = string.Format("The user says {0}.", s);
        DoAfterPostback1.DoAfterPostbackJavaScript = "showMsg('" + s + "');";
    }
}



Now run your project and enter value in textbox and click on button to test it.
If u have any problem in implementing this then feel free to contact me.
Amit Panchal
info@amitech.co
http://www.amitech.co

Friday, July 30, 2010

Caching output in asp.net to improve perfomance

Hello friends,
this post is to explain how to use caching in asp.net to improve performance of application.
whenever you make any function in your asp.net application you need to code it in the following way
public return_datatype Func_Name(datatype1 argument1,datatype2 argument2,datatype3 argument3,...)
    {
        string cacheKey = keyarray("Func_Name", argument1,argument2,argument3......);
        object cacheItem = HttpContext.Current.Cache[cacheKey];
        if ((cacheItem == null))
        {
            try
            {
                //logic of your actual function
               cacheItem=answer from your logic
            }
            catch (Exception ex)
            {
                cacheItem = (return_datatype) null;           }
            HttpContext.Current.Cache.Insert(cacheKey, cacheItem, null, absDate[put ur absolute date to expire cache memory], TimeSpan.Zero);
        }
        return (return_datatype)(cacheItem);
    }
public string keyarray(params object[] param)
    {
        string keyarr = "";
        foreach (object i in param)
            keyarr += "&" + i.ToString();
        return keyarr;
    } 
you will need keyarr method to generate unique keyarr for perticular function call
all done.
now when u call func_name function with parameters like (1,2,3...) it will be cached and when u again call the same function with same parameters it will return the answer from the cache memory.it will not go inside to execute ur logic again.
i hope you enjoyed this.
if you have any problem in implementing this then just email me at
info@amitech.co
Amit Panchal
http://amitech.co

Thursday, July 29, 2010

Automatics email sending using windows service

Hello friends,
we have seen so many web application which sends us emails notification at some regular time.
eg. if ur subscription is about to expire the system automatically notifies you by a mail.
it is very easy to do using windows service and web service.
to start first creat a web service in your asp.net project.
it will add filename.asmx ans filename.cs file in ur project.
open the filename.cs file and put your sending mail code in function like this.
  public string SendNotifications() {

        string msg = "This mail is sent from Mail Scheduler.
"+DateTime.Now.ToString();
        bool temp1=sendmail("toaddress", "fromaddress", "Mail Scheduler", msg);
       //put ur code to send email in sendmail function
        if (temp1)
        {return "Mail Sent"; }
       else { return "Error"; }
    }
now open visual studio and creat new project > windows service

and put the following code in your main service1.cs file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;

namespace Mail_Scheduler
{
    public partial class mailScheduler : ServiceBase
    {
        public System.Threading.Timer timer1;
        public mailScheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            int ticks = 1;
            if (args.Length > 0)
            {
                try { ticks = Convert.ToInt16(args[0]); }
                catch (Exception ex) { }
            }
            ticks = 60000 *60* ticks;
            this.timer1 = new Timer(new TimerCallback(this.timer1_Tick), null, 0,ticks);
            writeLog(DateTime.Now.ToString() + ": service started (Interval="+ticks.ToString()+")");
        }

        protected override void OnStop()
        {
            writeLog(DateTime.Now.ToString() + ": service stopped");
        }
        private void writeLog(string msg)
        {
            FileStream fs = new FileStream(@"c:\temp\mailScheduler.txt",
FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(msg+"\n");
            m_streamWriter.Flush();
            m_streamWriter.Close(); 
        }
        private void timer1_Tick(object stateInfo)
        {
            try
            {
                WebServiceRef.WebServiceSoapClient obj = new Mail_Scheduler.WebServiceRef.WebServiceSoapClient();
                string result = obj.SendNotifications();
                writeLog(DateTime.Now.ToString() + ": " + result);
            }
            catch (Exception ex) { }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            string result = DateTime.Now.ToString();
            writeLog(DateTime.Now.ToString() + "= " + result);
        }
    }
}
you need to add web reference of the webservice you just made, into ur windows service project.
and can use the method of webservice by creating an object of webservice.

now you are done.just create a setup of your windows service and install it.
to know more about how to create windows service click here
if you have any doubts feel free to contact me at info@amitech.co
Amit Panchal
www.amitech.co

Root Finding or finding Inverse function

Hello Friends,

In this post i will explain you how to get the inverse of a function or how to find the root of a function.
suppose there is a function y=f(x)
and you want the value of x when the y is 0 or something else.
you can find this solution using Numerical analytical mathamatics.
to use this algorithms.
download the source code from CodeProject
in this you will find a RootFinding.dll in source folder.
add reference of that file in your project.
and now you just need to make a class to use this dll.
RootFinder.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using RootFinding;

/// 
/// Summary description for RootFinder
/// 
public class RootFinder
{
    public RootFinder()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    // Newtons formel for iterativ lignings løsning
   private static double f (double x) {
        return (x*x-2*x+1); //replace this function by urs
    }
   public static double FindRoot(double x,double s,double e)
   {

       // Create the root finder object, that contains the algorithm

       BisectionRootFinder finder =
              new BisectionRootFinder(new UnaryFunction(f));

       // Define the accuracy you want for the root

       finder.Accuracy = 1.0E-04;

       // Prevent overflow

       finder.Iterations = 30;

       // Compute without bracketing outward
       try
       {
           return finder.Solve(s, e, false);
       }
       catch (Exception ex)
       {
           return FindRoot(0, s - 5, e + 5);
           //this was added letter on to expand the range of start value and end value.
       }
   }

}

you can call this method from your code using the following code
double temp=RootFinder.FindRoot(0,-1,1);

HTML to pdf

Hello friends,

i have searched a lot for exporting my webpage to pdf at server side and give option to download the web page in pdf format.
i found one component very interesting
http://www.winnovative-software.com/
this component takes url and export it to pdf but the problem is that it is too costly for me.
so i found another open source component.
http://www.itextpdf.com/
this component works fine but the problem is that it does not convert your html page to pdf directly.
you have to generate the pdf document manually by inserting records like a tabular form.
it takes html code as an input but it does not take stylesheet.
so it was not a good solution for me.
then i got a very good idea.and that is to convert my webpage first into image and then add that image to pdf using iTexhsharp open source component.
i searched for html to image component.
fortunately i got one free component that can capture the webpage as an image using URL.
to download the component  click here 

how to use this componet.
first create one class filecaptureweb.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public class CaptureWebPage
{
    private const string EXTRACTIMAGE_EXE = "IECapt.exe";
    private const int TIMEOUT = 120000;
    private string TMP_NAME = "Temp\\";

    public CaptureWebPage()
    {
    }

    private void Shot(string url, string rootDir)
    {
        Process p = new Process();
        p.StartInfo.FileName = rootDir + EXTRACTIMAGE_EXE;
        p.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", "--url="+url, "--out="+rootDir + TMP_NAME);
        //p.StartInfo.UseShellExecute = true;
        //p.StartInfo.CreateNoWindow = true;
        p.Start();
        p.WaitForExit();
        p.Dispose();
    }

    private System.Drawing.Image Scale(System.Drawing.Image imgPhoto, int Width, int Height)
    {
        int srcWidth = imgPhoto.Width;
        int srcHeight = imgPhoto.Height;
        int srcX = 0; int srcY = 0;
        int destX = 0; int destY = 0;

        float percent = 0; float percentWidth = 0; float percentHeight = 0;

        percentWidth = ((float)Width / (float)srcWidth);
        percentHeight = ((float)Height / (float)srcHeight);

        if (percentHeight < percentWidth)
        {
            percent = percentWidth;
            destY = 0;
        }
        else
        {
            percent = percentHeight;
            destX = 0;
        }

        int destWidth = (int)(srcWidth * percent);
        int destHeight = (int)(srcHeight * percent);

        System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(srcX, srcY, srcWidth, srcHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    public string GetImage(string url, string name, string rootDir, int width, int height)
    {
        TMP_NAME += name+".png";
        string fName = rootDir  + TMP_NAME;
        Shot(url, rootDir);
        System.Drawing.Image snapshotImage = System.Drawing.Image.FromFile(fName);
        fName = rootDir  + "OutPut" + "\\" + name + ".png";
        if (File.Exists(fName))
            File.Delete(fName);
        snapshotImage.Save(fName, ImageFormat.Png);
        return name+".png";
    }
} 

Now call this function from your code using the following code
private void saveURLToImage(string url, int Width, int Height,string filename)
    {
        CaptureWebPage cwp = new CaptureWebPage();
        string imagePath = cwp.GetImage(url, filename, Request.PhysicalApplicationPath.ToString(), Width, Height);
    } 


now this function will capture the webpage of url and will store in output folder of ur application.
please keep the IEcapt.exe in root folder.
now time to insert this image into pdf and send to browser for download,
use following function to add image into pdf and send to browser,
string attachment = "attachment; filename=" + InvID.ToString() + ".pdf";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/pdf";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        Document document = new Document();
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();
        //StringReader str = new StringReader(functions.RenderPage("http://localhost/invoice.aspx?invid"+InvID.ToString()));
        //HTMLWorker htmlworker = new HTMLWorker(document);
        //htmlworker.Parse(str);
        document.SetPageSize(PageSize.A4);
        string imageFilePath = Server.MapPath(".") + "/OutPut/" + InvID.ToString() + ".png";
        iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
        //Give space before image
        jpg.SpacingBefore = 30f;
        jpg.SpacingAfter = 1f;
        jpg.Alignment = Element.ALIGN_CENTER;
        jpg.ScalePercent(75);
        document.Add(jpg); //add an image to the created pdf document
        document.Close();
        Response.Write(document);
//you can add here your code to delete generated image file
        Response.End();
that's it. go for it now.
if you have any problem in using this feel free to email me at info@amitech.co
Amit Panchal
http://amitech.co

Wednesday, July 28, 2010

Modification to flot chart component

Hello friends,
flot is very good and flexible component to use for graphs and charts.
you can download the flot component from here.
this flot component provides bar chart and line chart.
line chart works fine but in bar chat you can display only two series of data.because it has only two option to align the data. left and center. if you have some more data series then it will overlap the existing data series.
so i have added one more option to alignment and that is right alignment.

if u want to display four data series then left right and center is not a good option to alignment,
so u can pass first,second,third and fourth as an alignment argument.

to get the modified version of click here
if you have any doubts feel free to email me at info@amitech.co
Amit Panchal
http://amitech.co

Monday, April 26, 2010

live updates while executing long process in asp.net

Hello friends,
if you have a long query or process to execute in ur asp.net application,
i have a very efficient and attractive looking program which u can use in ur application.
my project is in c#,
when u start executing the long process it shows the status of the process on the page in percentage. so user can know how much he needs to wait.
i can not post the code here.
if u want my help then contact me.
i will email u.

Screen Shot of my project


info@amitech.co
www.amitech.co

Friday, April 23, 2010

How to send values from one aspx page to another aspx page using "post method"

Problem:
How to send values from one aspx page to another aspx page using "post method"

Solution:
Create a class named RemotePost.vb
and add the following code in that class

Imports Microsoft.VisualBasic

Public Class RemotePost

    Private Inputs As System.Collections.Specialized.NameValueCollection = New System.Collections.Specialized.NameValueCollection

    Public Url As String = ""
    Public Method As String = "post"
    Public FormName As String = "form1"
    Public Sub Add(ByVal name As String, ByVal value As String)
        Inputs.Add(name, value)
    End Sub
    Public Sub Post()
        System.Web.HttpContext.Current.Response.Clear()
        System.Web.HttpContext.Current.Response.Write("")
        System.Web.HttpContext.Current.Response.Write(String.Format("", FormName))
        System.Web.HttpContext.Current.Response.Write(String.Format("


", FormName, Method, Url)) Dim i As Integer = 0 Do While i < Inputs.Keys.Count System.Web.HttpContext.Current.Response.Write(String.Format("", Inputs.Keys(i), Inputs(Inputs.Keys(i)))) i += 1 Loop System.Web.HttpContext.Current.Response.Write("
") System.Web.HttpContext.Current.Response.Write("") System.Web.HttpContext.Current.Response.End() End Sub End Class


now from any page from which u want to pass the value
use the following code

Dim myremotepost As RemotePost = New RemotePost
myremotepost.Url = "targetURL.aspx"
myremotepost.Add("param_name", "param_value")
myremotepost.Post()
 for c sharp version mail me
info@amitech.co
www.amitech.co

Paging in repeater,datalist or datagrid c#

Hello Friends,
if u want to use pagging in asp.net controls, i have the simplest method for it.

just use the following code:
filename.aspx.cs file

 
protected void Page_Load(object sender, EventArgs e)
{
FetchData();
}
private void FetchData()
{
int cur_page;
if (Convert.ToInt16(Request.QueryString["page"]) > 0)
{
cur_page = Convert.ToInt16(Request.QueryString["page"]);
}
else
{ cur_page = 0; }
DataClassesDataContext db_context = new DataClassesDataContext();
        var query = (from m in db_context.tbl_name
select m).Skip(cur_page * 10).Take(10);      
lblPageName.Text = "Page: " + (cur_page+1).ToString();
prevbut.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (cur_page - 1).ToString();
nextbut.NavigateUrl=Request.CurrentExecutionFilePath+"?page="+(cur_page+1).ToString();
        Repeaterid.DataSource = query;
        Repeaterid.DataBind();
}


filename.aspx

repeater

 

                                                    Previous
                                                    Next

if u have any problem in implementing this u can mail me at
info@amitech.co
www.amitech.co

Amitech

Hell0 Friends,
i know you are stuck with some serious problems and that's why you are here. So friends i m putting all the solved problems(with solution) that i have faced in my life (technical problems) on this blog.
In case you can not find the proper solutions, feel free to mail me at info@amitech.co
Amit Panchal