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);

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