Pages

Saturday 20 June 2015

Code to set ShortCut Keys in winforms

Introduction:
The shortcut keys are used to make your application user friendly and easy to use. But as you know there are some default short keys prepared by Microsoft Windows and some times you need to override these shortkeys.

Code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.B))  //Key combination
            {
                 // your code here
                return true;    // indicate that you handled this keystroke
            }

            if (keyData == Keys.Control) //Single Key
            {
                txtamount.Focus();
                return true;
            }

            // Call the base class
            return base.ProcessCmdKey(ref msg, keyData);
        }


Code to set default startup page in web.config

Introduction:

When someone opens your website by entering your domain name in the web browser then by default it will show the startup page. If you haven't setup an startup page than it will look for Default.aspx or index.html page in the source files. You can setup your startup page in web.config file.

Code:

  <system.webServer>
    <directoryBrowse enabled="false"/>
    <defaultDocument>
      <files>
        <clear/>
        <add value="Default.aspx"/>
      </files>
    </defaultDocument>
  </system.webServer>

URL mapping in web.config

Introduction :
URL mapping is very useful tool to make your URL look good and meaningful to site user. It will overcome the querystring issue. The user sometimes got confused with the parameters passed in the url in the form of querystring.

Code :
For url mapping you have to pace this code in the web.config file in <system.web></system.web> tag

    <urlMappings enabled="true">
      <add url="~/ComputerCourse" mappedUrl="~/courses.aspx?cid=2"/>
      <add url="~/ComputerHardware" mappedUrl="~/courses.aspx?cid=3"/>
      <add url="~/MobileRepairing" mappedUrl="~/courses.aspx?cid=4"/>
      <add url="~/CuttingTailoring" mappedUrl="~/courses.aspx?cid=5"/>
      <add url="~/Beautician" mappedUrl="~/courses.aspx?cid=6"/>
    </urlMappings>


Thursday 18 June 2015

Code to read content of Word/.doc file

Introduction: In this article I will explain how to read the content of a .doc file and show this in a Rich Textbox. And further we will filter the Email IDs form the content of the file.

NameSpace :
First of all you need to add a reference for ‘Microsoft.Office.Interop.Word’
And the use this namespace on your page.

using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
    
Code :
Here is the complete code:
private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op1 = new OpenFileDialog();
            op1.Multiselect = false;
            op1.ShowDialog();
            int count = 0;
            string[] FName;
            foreach (string s in op1.FileNames)
            {
                FName = s.Split('\\');
                //createting the object of application class 
                Microsoft.Office.Interop.Word.Application Objword = new Microsoft.Office.Interop.Word.Application();

                //creating the object of document class 
                Document objdoc = new Document();

                //get the uploaded file full path 
                dynamic FilePath = s;

                //pass the optional (missing) parameter to API 
                dynamic NA = System.Type.Missing;

                //open Word file document  
                objdoc = Objword.Documents.Open
                              (ref FilePath, ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA

                               );


                //creating the object of string builder class 
                StringBuilder sb = new StringBuilder();

                for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)
                {
                    string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();

                    if (Filedata != string.Empty)
                    {
                        //Append word files data to stringbuilder 
                        sb.AppendLine(Filedata);
                    }

                }

                //closing document object  
                ((_Document)objdoc).Close();

                //Quit application object to end process 
                ((_Application)Objword).Quit();

                //assign stringbuilder object to show text in textbox 
                richTextBox1.Text = Convert.ToString(sb);
            }


            // Code to Find Email Ids from the file content.
            MatchCollection mc;
            mc = Regex.Matches(richTextBox1.Text, "([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})");
            string res = (mc.Count - 1).ToString();
            for (int i = 0; i < mc.Count; i++)
            {
                MessageBox.Show (mc[i].Value);
            }
        }


Code to Receive Email using Outlook in C#

Introduction: Here is the code to read mail from outlook. The outlook is software developed by Microsoft to configure your mail box on your computer. And by using this code we can use outlook mails to process our requirement. The attachment with mails is also processed in this article.

NameSpace :
First of all you need to add a reference for ‘Microsoft.Office.Interop.Outlook’
And the use this namespace on your page.

using OutlookApplication = Microsoft.Office.Interop.Outlook;
    
Code :
Here is the complete code to read mails from outlook :

{
       OutlookApplication._Application outlook = new OutlookApplication.ApplicationClass();
            OutlookApplication._NameSpace Oname = outlook.GetNamespace("MAPI");

            Oname.Logon("your default outlook profile name", Missing.Value, false, false);
            OutlookApplication._SyncObject _syncObject = null;
            _syncObject = Oname.SyncObjects[1];
            _syncObject.Start();

            //System.Threading.Thread.Sleep(30000);

            _syncObject.Stop();
            _syncObject = null;

            Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = Oname.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            OutlookApplication.Items attachItems = myInbox.Items;

            string filter = "@SQL=" + "urn:schemas:httpmail:subject LIKE '%HELLO%' AND "
                                           + "urn:schemas:httpmail:datereceived >= '"
                                           + (DateTime.Now.ToUniversalTime()).ToString("MM/dd/yyyy") + "' AND "
                                           + "urn:schemas:httpmail:hasattachment = True";

            attachItems = attachItems.Restrict(filter);
            if (attachItems.Count > 0)
            {
                foreach (OutlookApplication.MailItem mail in attachItems)
                {
                    //mail.SenderEmailAddress;
                    foreach (OutlookApplication.Attachment attach in mail.Attachments)
                    {
                        //check for Path.GetExtension(attach.FileName) == ".zip"
                        if (attach.Size > 0 & attach.Type == OutlookApplication.OlAttachmentType.olByValue)
                        {
                            //SAVE FILE
                            mail.UnRead = false;
                        }
                    }
                }
            }

            attachItems = null;
            myInbox = null;
            Oname.Session.Logoff();
            Oname.Logoff();
            Oname = null;
            outlook.Quit();
            outlook = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
}


Code to EXPORT crystalreport to PDF

Introduction: In this article I will explain how to save the CrystalReport as PFD file. Saving pdf format of crystalreports is very important to keep the record.

Code :
Here is the complete code:

try
            {
                if (!Directory.Exists("D:\\Sanjeev\\"))
                {
                    Directory.CreateDirectory("D:\\Sanjeev\\");
                }
                ExportOptions CrExportOptions;
                DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                CrDiskFileDestinationOptions.DiskFileName = "D:\\Sanjeev\\newpdf.pdf";
                CrExportOptions = b.ExportOptions;
                {
                    CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                    CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                    CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                    CrExportOptions.FormatOptions = CrFormatTypeOptions;
                }
                b.Export();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }


Javascript code to add GRIDVIEW row

Introduction:  JavaScript Code to add row to a GridView.

Code:

<script type="text/javascript" lang="ja">
 function AddNewRecord() {
      var grd = document.getElementById('<%=gvportfolio.ClientID%>');
      var tbod = grd.rows[0].parentNode;
      var newRow = grd.rows[grd.rows.length - 1].cloneNode(true);
      tbod.appendChild(newRow);
      }

</script>

Sunday 14 June 2015

Connection String in Web.config

The web.config file stores the website configuration data, the connection string is used to store information on database connection.

The connection  string to connect to a local sql server database is :-

<connectionStrings>
    <add name="conn" connectionString="Data Source=.; Initial Catalog=DataBaseName; Integrated Security='True'" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The connection string to connect to a server :-

<connectionStrings>
    <add name="conn" connectionString="Server=ServerAddress; Database=DatabaseName; User ID=userID; Password=password; Trusted_Connection=False" />
  </connectionStrings>

Tuesday 9 June 2015

Upload file to FTP from windows form applications

Overview : Sometimes we need to upload some files to a web server from our desktop application. The file upload task is pretty easy in web applications but in desktop applications it is confusing because in websites we upload the files on the same server where we are working but in desktop applications we are working on a local computer and the server is come where else.
To overcome this issue I have created a function which will do this task for you.

public static void Fileuploader(string localpath, string username, string password)
        {
            var fileName = Path.GetFileName(localpath);
            var request = (FtpWebRequest)WebRequest.Create("ftp://www.example.com/httpdocs/_sft0258/" + fileName);

            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            using (var fileStream = File.OpenRead(localpath))
            {
                using (var requestStream = request.GetRequestStream())
                {
                    fileStream.CopyTo(requestStream);
                    requestStream.Close();
                }
            }

            var response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Success: {0}", response.StatusDescription);
            response.Close();
        }


By calling this function with correct parameters the upload file task will be completed smoothly.