Alhamdulillah Bersyukur Kepada Allah yang telah memberi kita semuanya

imam's posts with tag: c#

What are tags? You can give your posts a "tag", which is like a keyword. Tags help you find content which has something in common. You can assign as many tags as you wish to each post.
View posts by people in your network with tag c#
Blog EntrySource Code Web Mailmerge C#, continue from pastMar 26, '08 8:22 PM
for everyone

Berhubung projectnya udah lama sekali selesai dan expired berikut aku posting code utama dari webmailmerge menggunakan C# mungkin dapat digunakan sebagai bahan referensi.

Beberapa requirement yang harus diinstall
- Office Xp atau 2007 (msword & excel)
- GNU PDF Printer


#Code file: Upload.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.IO;
using System.IO.Compression;
using System.Xml;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using Microsoft.Office;
using Microsoft.Office.Core;
using System.Runtime.InteropServices;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Diagnostics;

using ICSharpCode.SharpZipLib.Zip;

/********external PROGRAM RUN class ********/
class RunProg{
  public RunProg()
  {
  }
  public void RunExecutable(string executable, string arguments)
  {
   ProcessStartInfo starter = new ProcessStartInfo(executable, arguments);
   starter.CreateNoWindow = true;
   starter.RedirectStandardOutput = true;
   starter.UseShellExecute = false;
   Process process = new Process();
   process.StartInfo = starter;
   process.Start();
   StringBuilder buffer = new StringBuilder();
   using (StreamReader reader = process.StandardOutput)
   {
    string line = reader.ReadLine();
    while (line != null)
    {
     buffer.Append(line);
     buffer.Append(Environment.NewLine);
     line = reader.ReadLine();
     Thread.Sleep(100);
    }
   }
   if (process.ExitCode != 0)
   {
    throw new Exception(string.Format(@"""{0}"" exited with ExitCode {1}. Output: {2}", executable, process.ExitCode, buffer.ToString())); 
   }
  }
}



/// Upload handler for uploading files.
public class Upload : IHttpHandler
{
    public Upload()
    {
    }

    #region IHttpHandler Members
    private HttpPostedFile htmltemplate;
    private string uploadpath;
    private string datasourcefile;
    private string datasourcetype;
    private string basepath;
    private DataSet sdataconf;
    private DataSet sdataset;
    private string outputtype;
    private string savein;
    private string loopingtags,starttag, closetag,  docinput;
    private bool debug;

    public bool IsReusable
    {
        get { return true; }
    }

    public void applyMerge()
    {
        if (docinputtype == "doc" || outputtype=="doc")
        {   //overridea as doc
            docinputtype = "doc";
            openTemplateDoc();
            applyMergeDoc();
            //dowlnload
            if (savein == "download") {
                FileOutput();
            }
            closeTemplateDoc();
            deleteTemplateDoc();

        }
        else if (docinputtype == "html") {
            openTemplateHTML();
            applyMergeHTML();
            //dowlnload
            if (savein == "download")
            {
                FileOutput();
            }
            closeTemplateHTML();
            deleteTemplateHTML();
        }
    }

    /***download: zip output and download as ZIP, need NET zip component***/
    private string filename;
    private string targetfile;
    private string html_ifolder,html_destfolder,html_base;
    private RunProg cmd_console;   
    private void FileOutput() {
        //create cmd external
        cmd_console = new RunProg();

        //rand str
        string randstr = DateTime.Now.Millisecond.ToString();

        //zipname
        string zipname = "output"+randstr+".zip";

        //fullpath of zipname target
        string zipoutput = this.outputpath+zipname;

        //generate random path
        string tempfolder=this.outputpath+"temp"+randstr+"\\";

        ///create random temp folder
        if (Directory.Exists(tempfolder)) Directory.Delete(tempfolder);
        Directory.CreateDirectory(tempfolder);

        ///move file to temp folder
        for (int i = 0; i < file_wrt.Count; i++)
        {
            filename = this.file_wrt[i].ToString();
            targetfile = tempfolder + System.IO.Path.GetFileName(filename);
            //HttpContext.Current.Response.Write("moving file: <b>" + filename + "</b> to <b>"+targetfile+"</b><br/>");
            if(File.Exists(filename)) File.Move(filename, targetfile);

            if (outputtype == "html") {
              html_base = System.IO.Path.GetFileNameWithoutExtension(filename) + "_files";
              html_ifolder=this.outputpath + html_base;
              html_destfolder = tempfolder ;
              if (Directory.Exists(html_ifolder)) {
                  string cmd = String.Format("/C move /Y \"{0}\" \"{1}\"", html_ifolder, html_destfolder);
                  //HttpContext.Current.Response.Write("run: <b>" + cmd + "</b><br/>");
                  cmd_console.RunExecutable("cmd.exe", cmd);
              }
            }

        }
        ///zip temp folder
        //HttpContext.Current.Response.Write("zip folder :" + tempfolder+"<br>");
        ZipDirectory(tempfolder,zipoutput);

        HttpContext.Current.Response.Write(String.Format("create zip file : <b>{0}</b> <a href=\"output/{1}\">click here for download zip</a><br/>",zipname,zipname));
        //recursive delete files in folder temp
        /*
        for (int i = 0; i < file_wrt.Count; i++)
        {
            filename = this.file_wrt[i].ToString();
            targetfile = tempfolder + System.IO.Path.GetFileName(filename);
            if(File.Exists(targetfile)) File.Delete(targetfile);
        }
        ///delete temp folder
        if (Directory.Exists(tempfolder)) Directory.Delete(tempfolder);
        */
        ///clean way to delete all files subfolder
        if (Directory.Exists(tempfolder))
        {
            string cmd = String.Format("/C RD /S /Q \"{0}\"", tempfolder);
            cmd_console.RunExecutable("cmd.exe", cmd);
        }


        ///create popup for download zip file
        string downloadurl = "downloadfile.aspx?zipfilename="+zipname;
        HttpContext.Current.Response.Write(String.Format("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"30,URL='{0}'\" /><script>window.open(\"{0}\")</script>", downloadurl));
        //HttpContext.Current.Response.Write("<BR>URL=" + downloadurl + "<br>");
    }
    public static void ZipDirectory(string sourceDirectory, string zipFileName)
    {
        (new FastZip()).CreateZip(zipFileName, sourceDirectory, true, null);
    }



    /*****PDF HANDLE*****/
    public PDFCreator.clsPDFCreator _PDFCreator;
    private PDFCreator.clsPDFCreatorError pErr;
    public bool ReadyState;
    private string fname;
    public string DefaultPrinter;
    private FileInfo fi;
    public PDFCreator.clsPDFCreatorOptions opt;
    public bool pdfstarted;
    private string parameters;

    public void initPDF()
    {
        if (pdfstarted) return;
        pErr = new PDFCreator.clsPDFCreatorError();
        _PDFCreator = new PDFCreator.clsPDFCreator();
        _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
        _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
        parameters = "/NoProcessingAtStartup";
            if (!_PDFCreator.cStart(parameters, false))
            {
                pdfstarted = false;
                HttpContext.Current.Response.Write("<font color=red>Printer Error Status: Error[" + pErr.Number + "]: " + pErr.Description + "<br/>Tell admin to Killall <b>PDFCreator.exe</b> on server</font><br/>");
                return;
            }
        pdfstarted = true;
    }


    public void WordPrintPDF(string Pfilefullname)
    {
        if (!pdfstarted) return;
        try
        {
            int FileTyp = 0;
            string destfolder = System.IO.Path.GetDirectoryName(Pfilefullname);
            fname = System.IO.Path.GetFileNameWithoutExtension(Pfilefullname);
            opt = _PDFCreator.cOptions;
            opt.UseAutosave = 1;
            opt.UseAutosaveDirectory = 1;
            opt.AutosaveDirectory = destfolder;
            opt.AutosaveFormat = FileTyp;
            opt.PDFOptimize = 1;
            opt.StandardSaveformat = 1;
            if (FileTyp == 5)
            {
                opt.BitmapResolution = 72;
            }
            opt.AutosaveFilename = fname;
            _PDFCreator.cOptions = opt;
            _PDFCreator.cClearCache();
            DefaultPrinter = _PDFCreator.cDefaultPrinter;
            _PDFCreator.cDefaultPrinter = "PDFCreator";
            _PDFCreator.cPrinterStop = false;
            this.ReadyState = false;
            _wordApplication.ActivePrinter = "PDFCreator";
            _wordApplication.PrintOut(ref oFalse, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue);
            int maxTime = 30; //in seconds
            int sleepTime = 250;
            int c = 0;
            int d = maxTime * 1000 / sleepTime;
            while (this.ReadyState == false && (c < d))
            {
                c = c + 1;
                Thread.Sleep(100);
            }
            _PDFCreator.cPrinterStop = true;
            _PDFCreator.cDefaultPrinter = DefaultPrinter;
            if (this.debug) HttpContext.Current.Response.Write("output:" + _PDFCreator.cOutputFilename + "<br>");
            swordoutputfile = _PDFCreator.cOutputFilename;
            ReadyState = false;
        }
        catch (Exception ecp)
        {
            HttpContext.Current.Response.Write("Error exception: <b>" + ecp.Message.ToString() + "</b><br/>");

        }
    }

    public void PrintFile(string Pfilefullname, string destfolder)
    {
        if (!pdfstarted) return;
        if (!File.Exists(Pfilefullname))
        {
            HttpContext.Current.Response.Write("<font color=red>Error:" + Pfilefullname + " is not exists!</font><br>");
            return;
        }
        if (!_PDFCreator.cIsPrintable(Pfilefullname))
        {
            HttpContext.Current.Response.Write("<font color=red>Error:" + Pfilefullname + " is not printable!</font><br>");
            return;
        }
        try
        {
            int FileTyp = 0;
            fi = new FileInfo(Pfilefullname);
            fname = fi.Name;
            if (fname.IndexOf(".") > 0) fname = fname.Substring(0, fname.IndexOf("."));
            opt = _PDFCreator.cOptions;
            opt.UseAutosave = 1;
            opt.UseAutosaveDirectory = 1;
            opt.AutosaveDirectory = destfolder;
            opt.AutosaveFormat = FileTyp;
            opt.PDFOptimize = 1;
            opt.StandardSaveformat = 1;
            if (FileTyp == 5)
            {
                opt.BitmapResolution = 72;
            }
            opt.AutosaveFilename = fname;
            _PDFCreator.cOptions = opt;
            _PDFCreator.cClearCache();
            DefaultPrinter = _PDFCreator.cDefaultPrinter;
            _PDFCreator.cDefaultPrinter = "PDFCreator";
            _PDFCreator.cPrintFile(fi.FullName);
            _PDFCreator.cPrinterStop = false;
            this.ReadyState = false;
            int maxTime = 30; //in seconds
            int sleepTime = 250;
            int c = 0;
            int d = maxTime * 1000 / sleepTime;
            while (this.ReadyState == false && (c < d))
            {
                c = c + 1;
                Thread.Sleep(100);
            }
            _PDFCreator.cPrinterStop = true;
            _PDFCreator.cDefaultPrinter = DefaultPrinter;
            //if (this.debug) HttpContext.Current.Response.Write("output:" + _PDFCreator.cOutputFilename + "<br>");
            swordoutputfile = _PDFCreator.cOutputFilename;
            ReadyState = false;
        }
        catch (Exception ecp)
        {
            HttpContext.Current.Response.Write("Error exception: <b>" + ecp.Message.ToString() + "</b><br/>");

        }
    }

    private void _PDFCreator_eReady()
    {
        _PDFCreator.cPrinterStop = true;
        this.ReadyState = true;
        //HttpContext.Current.Response.Write("ready state: <b>" + this.swordoutputfile + "</b><br/>");
    }

    public void _PDFCreator_eError()
    {
        try
        {
            pErr = _PDFCreator.cError;
            _PDFCreator.cPrinterStop = true;
            _PDFCreator.cDefaultPrinter = DefaultPrinter;
            _PDFClose_END();
        }
        catch { }
    }

    public void _PDFClose_END()
    {
        try
        {
            _PDFCreator.cClose();
            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_PDFCreator) > 0) ;
            _PDFCreator = null;
            pErr = null;
            GC.Collect();
        }
        catch(Exception ecp)
        {
            HttpContext.Current.Response.Write("Error exception: <b>" + ecp.Message.ToString() + "</b><br/>");
        }
    }
   
   

    /***string replacement for filename***/
    private string FixFileName(string s_outputfilename){
      s_outputfilename=s_outputfilename.Replace(" ", "_").Trim("'!@#$%^&*()_+".ToCharArray());
      return s_outputfilename;
    }

    /*doc handle*/
    private object oFalse, oTrue, oInpuTFile;
    public Word._Application _wordApplication;
    public Word._Document _wordDocument;
    private object oOutpuTFile, oFileFormat;
    private string swordoutputfile;

    private void applyMergeDoc(){
        if (datasourcetype == "xml") {
            readXMLDataSourceRow();
        }
        else if (datasourcetype == "excel")
        {
            readExcelDataSourceRow();
        }
    }
   

    private void openTemplateDoc()
    {
        //open app
        _wordApplication = null;
        _wordApplication = new Word.Application();
        _wordApplication.Visible = false;
        nullValue = Missing.Value;
        oTrue = true;
        oFalse = false;
    }

    private void docReplace(string s_tag2replace, string s_val2assign)
    {
        //HttpContext.Current.Response.Write("word replace : <b>" + s_tag2replace + "</b> with <b>" + s_val2assign + "</b><br/>");
        object vk_find = s_tag2replace;
        object vk_replace = s_val2assign;
        object vk_num = 1;
        object vk_read_only = false;
        object vk_visible = true;
        object vk_false = false;
        object vk_true = true;
        object vk_dynamic = 2;
        _wordApplication.Selection.Find.Execute(ref vk_find, ref vk_false, ref vk_false,
        ref vk_false, ref vk_false, ref vk_false, ref vk_true, ref vk_num, ref vk_false,
        ref vk_replace, ref vk_dynamic, ref vk_false, ref vk_false, ref vk_false, ref vk_false);
    }

    private void closeTemplateDoc()
    {
        _wordApplication.Quit(ref oFalse, ref nullValue, ref nullValue);
        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_wordApplication) > 0) ;
        _wordApplication = null;
    }

    private void deleteTemplateDoc() {
        //HttpContext.Current.Response.Write("word delete: <b>" + docinput + "</b><br/>");
        if (File.Exists(docinput)) File.Delete(docinput);
    }

    private void docInitNewPage() {
        oInpuTFile = docinput;
        _wordDocument = _wordApplication.Documents.Open(ref oInpuTFile, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue);
        //HttpContext.Current.Response.Write("init page: <b>"+docinput +" --</b><br/>");
    }

    private void docClosePage() {
        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_wordDocument) > 0) ;
        _wordDocument = null;
    }

    private void docWritePage() {
        //format output
        switch (outputtype)
        {
            case "doc": oFileFormat = Word.WdSaveFormat.wdFormatDocument; swordoutputfile = swordoutputfile + ".doc"; break;
            case "html": oFileFormat = Word.WdSaveFormat.wdFormatHTML; swordoutputfile = swordoutputfile + ".html"; break;
            case "pdf": oFileFormat = Word.WdSaveFormat.wdFormatDocument; swordoutputfile = swordoutputfile + ".doc"; break;
            default: oFileFormat = Word.WdSaveFormat.wdFormatDocument; swordoutputfile = swordoutputfile + ".doc"; break;
        }

        //print PDF
        if (outputtype == "pdf")
        {
            //write ouput file
            this.WordPrintPDF(swordoutputfile);
            _wordDocument.Close(ref oFalse, ref nullValue, ref nullValue);
            Thread.Sleep(100);
        }
        else
        {
            //write ouput file
            oOutpuTFile = swordoutputfile;
            if (File.Exists(swordoutputfile)) File.Delete(swordoutputfile);
            _wordDocument.SaveAs(ref oOutpuTFile, ref oFileFormat, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue, ref nullValue);
            _wordDocument.Close(ref oTrue, ref nullValue, ref nullValue);
        }
       
        //close page
        this.docClosePage();

        //add to arraylist
        file_wrt.Add(swordoutputfile);

        /*writing*/
        string downloadstr = "output/" + System.IO.Path.GetFileName(swordoutputfile);
        HttpContext.Current.Response.Write("writing files:: <b>" + swordoutputfile + "</b> <a href=\"" + downloadstr + "\">download</a><br><br>");

       
    }

/*html handle*/
    private void applyMergeHTML() {
        if (datasourcetype == "xml")
        {
            readXMLDataSourceRow();
        }
        else if (datasourcetype == "excel")
        {
            readExcelDataSourceRow();
        }
    }

    private string bufferHTML,newStringHTML;

    private void openTemplateHTML()
    {
        //HttpContext.Current.Response.Write("HTML open: <b>" + docinput + "</b><br/>");
        //reading input
        StreamReader objReader = new StreamReader(docinput);
        bufferHTML = objReader.ReadToEnd();
        objReader.Close();
    }
    private void closeTemplateHTML()
    {
        //HttpContext.Current.Response.Write("HTML close: <b>" + docinput + "</b><br/>");
    }
    private void deleteTemplateHTML()
    {
        //HttpContext.Current.Response.Write("HTML delete: <b>" + docinput + "</b><br/>");
        if (File.Exists(docinput)) File.Delete(docinput);
    }

    private void HTMLInitNewPage()
    {
        newStringHTML = bufferHTML;
    }
    private void HTMLReplace(string s_tag2replace, string s_val2assign)
    {
        //HttpContext.Current.Response.Write("word replace : <b>" + s_tag2replace + "</b> with <b>" + s_val2assign + "</b><br/>");
        newStringHTML=newStringHTML.Replace(s_tag2replace, s_val2assign);
    }
    private void HTMLWritePage()
    {
        switch (outputtype)
        {
            case "html": swordoutputfile = swordoutputfile + ".html"; break;
            case "pdf": swordoutputfile = swordoutputfile + ".html"; break;
            default: swordoutputfile = swordoutputfile + ".html"; break;
        }
        FileInfo fleNewFile = new FileInfo(swordoutputfile);
        StreamWriter swrNewFile = fleNewFile.CreateText();
        swrNewFile.Write(newStringHTML);
        swrNewFile.Flush();
        swrNewFile.Close();
        newStringHTML = "";

        if(outputtype=="pdf"){
            string lastfile = swordoutputfile;
            this.PrintFile(swordoutputfile, this.outputpath);
            if(File.Exists(lastfile)) File.Delete(lastfile);
        }
       
        file_wrt.Add(swordoutputfile);

        /*writing*/
        string downloadstr = "output/"+System.IO.Path.GetFileName(swordoutputfile);
        HttpContext.Current.Response.Write("writing files:: <b>" + swordoutputfile + "</b> <a href=\"" + downloadstr + "\">download</a><br>");
       
    }


 /*xml datasource*/
    private string tblname0;
    private String[] alooptags;

    private void openXMLDataSource(){
        sdataset = new DataSet();
        sdataset.ReadXml(datasourcefile);
        //HttpContext.Current.Response.Write("reading xml: <b>" + datasourcefile.ToString() + "</b><br/>");
        alooptags = loopingtags.Split(',');
        tblname0 = alooptags[0].ToString();
    }
    private void readXMLDataSourceRow(){
        for (int row = 0; row < sdataset.Tables[tblname0].Rows.Count; row++)
        {
            ///doc init page
            if (docinputtype == "doc") docInitNewPage();
            else if(docinputtype == "html") HTMLInitNewPage();

            string s_outputfilename = outputfilename;
            for (int tb = 0; tb < alooptags.Length; tb++)
            {
                string tblname = alooptags[tb].ToString();

                if (row < sdataset.Tables[tblname].Rows.Count)
                {
                    DataRow dtr = sdataset.Tables[tblname].Rows[row];
                    for (int col = 0; col < sdataset.Tables[tblname].Columns.Count; col++)
                    {
                        DataColumn c = sdataset.Tables[tblname].Columns[col];
                        string tag2replace = starttag + tblname + "." + c.ColumnName + closetag;
                        string val2assign= dtr[c.ColumnName].ToString();
                        //doc replace
                        if (docinputtype == "doc") docReplace(tag2replace, val2assign);
                        else if (docinputtype == "html") HTMLReplace(tag2replace, val2assign);
                        //filename replace
                        s_outputfilename = s_outputfilename.Replace(tag2replace, val2assign);
                    }
                }
            }

            if (s_outputfilename == "" || s_outputfilename == outputfilename) s_outputfilename = row.ToString();
            swordoutputfile = string.Format("{0}{1}", outputpath, FixFileName(s_outputfilename));
                   
            //doc writepage
            if (docinputtype == "doc") docWritePage();
            else if (docinputtype == "html") HTMLWritePage();
        }
    }
    private void closeXMLDataSource() {
        sdataset = null;

    }
       
 /*excel datasource*/
    public Excel._Application excelApp;
    public Excel.Workbook excelWorkbook;
    public Excel.Worksheet excelWorksheet;
    public Excel.Sheets excelSheets;
    private object nullValue;
    private OleDbConnection con;
    private OleDbDataAdapter da;
    private DataTable tbl,tbl2;
    public void openExcelDataSource() {
        nullValue = Missing.Value;
        oFalse = false;
    }

    public void closeExcelDataSource() {
    }

    private void readExcelDataSourceRow() {
       
        con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + datasourcefile + ";Extended Properties=Excel 8.0");
        //get all sheet name
        con.Open();
        tbl2 = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if(tbl2 == null) return ;
        String[] excelSheets = new String[tbl2.Rows.Count];
        int i = 0;
        foreach(DataRow tblrow in tbl2.Rows)
        {
          excelSheets[i] = tblrow["TABLE_NAME"].ToString();
          i++;
        }
       
        tbl2=null;

        foreach (string currentSheet in excelSheets)
        {
            string s_currentSheet = currentSheet.Replace("$", "");
            da = new OleDbDataAdapter("select * from [" + currentSheet + "]", con);
            tbl = new DataTable();
            da.Fill(tbl);
            if (tbl.Columns.Count > 1)
            {
                for (int row = 0; row < tbl.Rows.Count; row++)
                {
                    ///doc init page
                    if (docinputtype == "doc") docInitNewPage();
                    else if (docinputtype == "html") HTMLInitNewPage();
                    DataRow dtr = tbl.Rows[row];
                    string s_outputfilename = outputfilename;
                    for (int col = 0; col < tbl.Columns.Count; col++)
                    {
                        DataColumn c = tbl.Columns[col];
                        string tag2replace = starttag + s_currentSheet + "." + c.ColumnName + closetag;
                        string val2assign = dtr[c.ColumnName].ToString();
                        //doc replace
                        if (docinputtype == "doc") docReplace(tag2replace, val2assign);
                        else if (docinputtype == "html") HTMLReplace(tag2replace, val2assign);
                        //filename replace
                        s_outputfilename = s_outputfilename.Replace(tag2replace, val2assign);

                    }
                    if (s_outputfilename == "" || s_outputfilename == outputfilename) s_outputfilename = row.ToString();
                    swordoutputfile = string.Format("{0}{1}", outputpath, FixFileName(s_outputfilename));
                    //doc writepage
                    if (docinputtype == "doc") docWritePage();
                    else if (docinputtype == "html") HTMLWritePage();
                }
            }
           
            tbl = null;
            da = null;
        }
        con.Close();
        con = null;
    }


/*******init start request************/
    private string docinputtype;
    private string outputfilename;
    private string outputpath;
    private ArrayList file_wrt;
    private bool fileuploaded = false;
   
   
    public void ProcessRequest(HttpContext context)
    {
        this.debug = false;

        HttpContext.Current.Response.Write("<html><head><title>Output Result</title></head><body>");

        try
        {
            //parsing config
            sdataconf = new DataSet();
            basepath = HttpContext.Current.Request.PhysicalApplicationPath;
            sdataconf.ReadXml(basepath + "config.xml");
            uploadpath = basepath + "upload\\";
            outputpath = basepath + "output\\";
            datasourcetype = sdataconf.Tables["customconfig"].Rows[0]["datasourcetype"].ToString();
            datasourcefile = basepath + sdataconf.Tables["customconfig"].Rows[0]["datasourcefile"].ToString();
            starttag = sdataconf.Tables["customconfig"].Rows[0]["starttag"].ToString();
            closetag = sdataconf.Tables["customconfig"].Rows[0]["closetag"].ToString();
            loopingtags = sdataconf.Tables["customconfig"].Rows[0]["loopingtags"].ToString();

            //htmltemplate    
            htmltemplate = context.Request.Files["inputfile"];
            outputtype = context.Request["outputtype"].ToString();
            outputfilename = context.Request["outputfilename"].ToString();
            savein = context.Request["savein"].ToString();
        }
        catch { }

        //array for file zip
        file_wrt = new ArrayList();

        if (context.Request.Files.Count > 0 && htmltemplate!=null)
        {
       
            docinput = string.Format("{0}{1}", uploadpath, System.IO.Path.GetFileName(htmltemplate.FileName));
            string inputextension = System.IO.Path.GetExtension(htmltemplate.FileName);
           
            if(inputextension==".doc") docinputtype="doc";
            else if(inputextension==".html" ||inputextension==".htm") docinputtype="html";

            if (htmltemplate != null && htmltemplate.ContentLength != 0)
            {

                try
                {
                    //save template
                    htmltemplate.SaveAs(docinput);
                    fileuploaded = true;

                    //write status
                    // HttpContext.Current.Response.Write("docinput: <b>" + docinput.ToString() + "</b><br>");
                    // HttpContext.Current.Response.Write("uploadpath: <b>" + uploadpath.ToString() + "</b><br/>");
                    // HttpContext.Current.Response.Write("datasourcetype: <b>" + datasourcetype.ToString() + "</b><br>");
                    // HttpContext.Current.Response.Write("datasourcefile: <b>" + datasourcefile.ToString() + "</b><br>");
                    if (File.Exists(datasourcefile))
                    {
                        if (datasourcetype == "excel" && System.IO.Path.GetExtension(datasourcefile) == ".xls")
                        {
                            if (outputtype == "pdf")
                            {
                                this.initPDF();
                                if (!pdfstarted) return;
                            }
                            openExcelDataSource();
                            applyMerge();
                            closeExcelDataSource();
                            if (outputtype == "pdf") this._PDFClose_END();
                        }
                        else if (datasourcetype == "xml" && System.IO.Path.GetExtension(datasourcefile) == ".xml")
                        {
                            if (outputtype == "pdf")
                            {
                                this.initPDF();
                                if (!pdfstarted) return;
                            }
                            openXMLDataSource();
                            applyMerge();
                            closeXMLDataSource();
                            if (outputtype == "pdf") this._PDFClose_END();
                        }
                    }
                }
                catch (Exception ecp)
                {
                    HttpContext.Current.Response.Write("Error: "+ecp.Message.ToString());
                }

            }
        }
       
       
        if(!fileuploaded){
            HttpContext.Current.Response.Write("Error, no input files <a href=\"default.aspx\">Back</a>");
        }
        HttpContext.Current.Response.Write("</body></html>");
    }

    #endregion


}


dan untuk link fullsource dapat di download pada link attachment posting
http://iferianto.multiply.com/journal/item/83/Source_Code_Web_Mailmerge_C_continue_from_past
Attachment: mailmerge-v1.rar

© 2008 Multiply, Inc.    About · Blog · Terms · Privacy · Corp Info · Contact Us · Help