Saturday, October 21, 2017

Reading Data form Notepad using File InputOutput


                    FileStream fs1 = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader sr = new StreamReader(fs1);
               
          String      str = sr.ReadLine();
             int   a1 = int.Parse(str);

           String     str1 = sr.ReadLine();
            int    a2 = int.Parse(str1);




   string[] n = Regex.Split(s, "\n");//here we are spliting the string based on new line into a array
                                    if (n.Length > LINES) //here LINES is Index no.
                                    {
                                      

                                        for (int i = LINES; i < n.Length; i++)
                                        {

                                            string S1;
                                            S1 = n[i];

                                            if (S1 != "")
                                            {
                                                LINES++;



}

}

Window Services


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace ranjeetServices
{
    public partial class Service1 : ServiceBase
    {
        System.Threading.Thread mythread;
        public Service1()
        {
            InitializeComponent();
            mythread = new System.Threading.Thread(new System.Threading.ThreadStart(dosomething));
        }
      





        protected override void OnStart(string[] args)
        {
            mythread.Start();
        }




        private void dosomething()
        {
            try
            {
                ProcessStartInfo info = new ProcessStartInfo(@"C:\rk\services\insert.exe");
                info.CreateNoWindow = true;
                info.UseShellExecute = false;
                Process.Start(info);
              
            }
            catch(Exception) {

             
            }
          
        }






        protected override void OnStop()
        {
            try
            {
                mythread.Join(10000);
                foreach (Process clsProcess in Process.GetProcesses())
                {
                    if (clsProcess.ProcessName == "Ranjeet")
                    {
                        try
                        {
                            clsProcess.Kill();
                        }
                        catch { }
                    }


                }
                foreach (Process clsProcess in Process.GetProcesses())
                {
                    if (clsProcess.ProcessName == "Ranjeet_Service.exe")
                    {
                        try
                        {
                            clsProcess.Kill();
                        }
                        catch { }
                    }


                }
            }
            catch (Exception)
            {

              
            }
        }
    }
}

Note:  Rajeet_Service    is Renamed itself service name to bin folder

Reading PDF Using C#

Required Dll: itextsharp.dll


 using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PDF_READING_BY_RANJEET
{
    class Program
    {
        static void Main(string[] args)
        {


           
            string currentText = string.Empty;
            string currentLine;

            int flag = 0;

            PdfReader pdfReader = new PdfReader(@"D:\rk.pdf");


            for (int page = 3; page <= pdfReader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                currentText = currentText + PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy) + Environment.NewLine;
            }




            //...............................................start....................1................................................................



            using (var reader = new StringReader(currentText))
            {

                while ((currentLine = reader.ReadLine()) != null)
                {

                SecondTimeSTD: //here it will come second time not first time

                    if (currentLine.IndexOf("Xyz. Contain", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {

                        while ((currentLine = reader.ReadLine()) != null)
                        {


                            if ((currentLine.Contains(":") && currentLine.Contains("-")) && currentLine.Contains(":") && currentLine.Contains("."))
                            {

                            
                                string[] processCDR = currentLine.Split(' ');

                                int ranjeetCount = processCDR.Count();
                                if (ranjeetCount == 7)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database

                                }

                                if (ranjeetCount == 12)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database



                                    string time2 = processCDR[6];
                                    string calledno2 = processCDR[7];
                                    string destination3 = processCDR[8];
                                    string duration4 = processCDR[9];
                                    string callunit5 = processCDR[10];
                                    string chargaes6 = processCDR[11];
                                    //second insert into database

                                }
                            }
                            else if (currentLine.IndexOf("Xyz. Contain-2", StringComparison.InvariantCultureIgnoreCase) != -1)
                            {

                                goto ISD_Section;

                            }
                        }



                   }



                ISD_Section:
                if (currentLine.IndexOf("Xyz. Contain-3", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {

                        while ((currentLine = reader.ReadLine()) != null)
                        {


                            if ((currentLine.Contains(":") && currentLine.Contains(":") && currentLine.Contains(".")))
                            {

                             


                                string[] processCDR = currentLine.Split(' ');

                                int ranjeetCount = processCDR.Count();
                                if (ranjeetCount == 7)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database

                                }

                                if (ranjeetCount == 12)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database



                                    string time2 = processCDR[6];
                                    string calledno2 = processCDR[7];
                                    string destination3 = processCDR[8];
                                    string duration4 = processCDR[9];
                                    string callunit5 = processCDR[10];
                                    string chargaes6 = processCDR[11];
                                    //second insert into database

                                }
                            }
                            else if (currentLine.IndexOf("Xyz. Contain-4", StringComparison.InvariantCultureIgnoreCase) != -1)
                            {

                                goto ZonalCall;

                            }
                        }


                    }







                ZonalCall:

                    flag++;

                    if (currentLine.IndexOf("Xyz. Contain-4", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {

                        while ((currentLine = reader.ReadLine()) != null)
                        {


                            if ((currentLine.Contains(":") && currentLine.Contains("-")) && currentLine.Contains(":") && currentLine.Contains("."))
                            {

                             

                                string[] processCDR = currentLine.Split(' ');

                                int ranjeetCount = processCDR.Count();
                                if (ranjeetCount == 7)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database

                                }

                                if (ranjeetCount == 12)
                                {
                                    string time = processCDR[0];
                                    string calledno = processCDR[1];
                                    string destination = processCDR[2];
                                    string duration = processCDR[3];
                                    string callunit = processCDR[4];
                                    string chargaes = processCDR[5];
                                    //first insert into database



                                    string time2 = processCDR[6];
                                    string calledno2 = processCDR[7];
                                    string destination3 = processCDR[8];
                                    string duration4 = processCDR[9];
                                    string callunit5 = processCDR[10];
                                    string chargaes6 = processCDR[11];
                                    //second insert into database

                                }
                            }


                            else if (flag == 65)
                            {
                                if (currentLine.IndexOf("abc", StringComparison.InvariantCultureIgnoreCase) != -1)
                                {

                                    goto SecondTimeSTD;


                                }
                            }

                        
                        }


                    }














                }




            }
        //................end....................1................................................................












            ExitPDF:


            Console.WriteLine("I am going Out ranjeet");







        }
   
       
    }
}

Generate PDF and Send Attachment throungh Mail


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Data;
using System.Net;
using System.Net.Mail;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class CS : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] {
                            new DataColumn("EmpId"),
                            new DataColumn("Call"),
                            new DataColumn("Time")});
            dt.Rows.Add("SAM123", "STD", "5:20");
            dt.Rows.Add("SAM124", "ISD", "7:20");
            dt.Rows.Add("SAM125", "LOCAL", "9:20");
            dt.Rows.Add("SAM126", "INTERNAL", "3:20");
            SendPDFEmail(dt);
        }
    }

    private void SendPDFEmail(DataTable dt)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                string companyName = "Mindtree Ltd.";
                string rtype = "admin";
                StringBuilder sb = new StringBuilder();
                sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Mail Details</b></td></tr>");
                sb.Append("<tr><td colspan = '2'></td></tr>");
                sb.Append("<tr><td><b>Report Type:</b>");
                sb.Append(rtype);
                sb.Append("</td><td><b>Date: </b>");
                sb.Append(DateTime.Now);
                sb.Append(" </td></tr>");
                sb.Append("<tr><td colspan = '2'><b>Company Name :</b> ");
                sb.Append(companyName);
                sb.Append("</td></tr>");
                sb.Append("</table>");
                sb.Append("<br />");
                sb.Append("<table border = '1'>");
                sb.Append("<tr>");
                foreach (DataColumn column in dt.Columns)
                {
                    sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
                    sb.Append(column.ColumnName);
                    sb.Append("</th>");
                }
                sb.Append("</tr>");
                foreach (DataRow row in dt.Rows)
                {
                    sb.Append("<tr>");
                    foreach (DataColumn column in dt.Columns)
                    {
                        sb.Append("<td>");
                        sb.Append(row[column]);
                        sb.Append("</td>");
                    }
                    sb.Append("</tr>");
                }
                sb.Append("</table>");
                StringReader sr = new StringReader(sb.ToString());

                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                    pdfDoc.Open();
                    htmlparser.Parse(sr);
                    pdfDoc.Close();
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();

                    MailMessage mm = new MailMessage("ranjeet@gmail.com", "ranjeet@gmail.com");
                    mm.Subject = "Mindtree Historical Weekly Mail";
                    mm.Body = "Report Mail";
                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "admin.pdf"));
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential();
                    NetworkCred.UserName = "ranjeet@gmail.com";
                    NetworkCred.Password = "xyz";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}

Folder Zipping and Moving to Other Drive


 Requered this Dll:  Ionic.Zip.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ionic.Zip;
using System.Threading;

namespace segregation
{
    public partial class Move_Files : Form
    {

        public Move_Files()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void btnMove_Click(object sender, EventArgs e)
        {
        

            string path = txtPath.Text.Trim();
            string pathToMove = txtPathMove.Text.Trim();

            DirectoryInfo di = new DirectoryInfo(path);
            string[] files = Directory.GetFiles(path);


            //The following piece of code is for arranginging raw data files to respective datewise directories
            for (int i = 0; i < files.Length; i++)
            {
                string[] arr = files[i].Split('_');
                arr[3] = arr[3].Substring(0, 8);
                arr[3] = arr[3].Insert(4, "-");
                arr[3] = arr[3].Insert(7, "-");
                string path2 = pathToMove + "\\" + arr[3];
                string path3 = pathToMove + "\\" + arr[3] + "\\" + arr[1] + "_" + arr[2] + "_" + arr[3] + "_" + arr[4];
                if (!Directory.Exists(path2))
                {
                    Directory.CreateDirectory(path2);
                    try
                    {
                        File.Move(files[i], path3);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    try
                    {
                        File.Move(files[i], path3);
                    }
                    catch (Exception ex1)
                    {
                        MessageBox.Show(ex1.ToString());
                    }

                }
            }
            //The following piece of code is for moving respective organized datewise folders to monthly organized folders
            DirectoryInfo di1 = new DirectoryInfo(pathToMove);
            string[] files1 = Directory.GetDirectories(pathToMove);

            int monthNo = 0;
            string monthName = string.Empty;
            string path4 = string.Empty;
            string path5 = string.Empty;
            for (int j = 0; j < files1.Length; j++)
            {
              
                string[] arr1 = files1[j].Split('\\', '-');

                if(arr1.Length==5)//One folder
                {
                     monthNo = Int32.Parse(arr1[3]);

                     monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                     path4 = pathToMove + "\\" + monthName + " " + arr1[2];
                      path5 = path4 + "\\" + arr1[2] + "-" + arr1[3] + "-" + arr1[4];
                }
                else if(arr1.Length==6)//Two folder
                {
                    monthNo = Int32.Parse(arr1[4]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                    path4 = pathToMove + "\\" + monthName + " " + arr1[3];
                    path5 = path4 + "\\" + arr1[3] + "-" + arr1[4] + "-" + arr1[5];
                }

                else if (arr1.Length == 7)//Three folder
                {
                    monthNo = Int32.Parse(arr1[5]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                     path4 = pathToMove + "\\" + monthName + " " + arr1[4];
                    path5 = path4 + "\\" + arr1[4] + "-" + arr1[5] + "-" + arr1[6];
                }
                else if (arr1.Length == 8)//Four folder
                {
                    monthNo = Int32.Parse(arr1[6]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                     path4 = pathToMove + "\\" + monthName + " " + arr1[5];
                     path5 = path4 + "\\" + arr1[5] + "-" + arr1[6] + "-" + arr1[7];
                }
                else if (arr1.Length == 9)//Five folder
                {
                    monthNo = Int32.Parse(arr1[7]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                    path4 = pathToMove + "\\" + monthName + " " + arr1[6];
                    path5 = path4 + "\\" + arr1[6] + "-" + arr1[7] + "-" + arr1[8];
                }
                else if (arr1.Length == 10)//Six folder
                {
                    monthNo = Int32.Parse(arr1[8]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                    path4 = pathToMove + "\\" + monthName + " " + arr1[7];
                    path5 = path4 + "\\" + arr1[7] + "-" + arr1[8] + "-" + arr1[9];
                }
                else if (arr1.Length == 11)//Seven folder
                {
                    monthNo = Int32.Parse(arr1[9]);
                    monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNo);
                    path4 = pathToMove + "\\" + monthName + " " + arr1[8];
                    path5 = path4 + "\\" + arr1[8] + "-" + arr1[9] + "-" + arr1[10];
                }
                else
                {
                    MessageBox.Show("Too Long Path!");
                }


                if (!Directory.Exists(path4))
                {
                    Directory.CreateDirectory(path4);
                    try
                    {
                        Directory.Move(files1[j], path5);
                    }
                    catch (Exception ex2)
                    {
                        MessageBox.Show(ex2.ToString());
                    }
                }
                else
                {
                    try
                    {
                        Directory.Move(files1[j], path5);
                    }
                    catch (Exception ex3)
                    {
                        MessageBox.Show(ex3.ToString());
                    }
                }
            }
            MessageBox.Show("Congratulations! Your all files are moved successfully");
        }
        private void btnZip_Click(object sender, EventArgs e)
        {
            string path6 = txtPathMove.Text.Trim();
            DirectoryInfo di3 = new DirectoryInfo(path6);
            string[] files2 = Directory.GetDirectories(path6);


            //The following code is for zipping monthly data folders, subfolders and files.
            for (int k = 0; k < files2.Length; k++)
            {

                string path7 = files2[k];
                string ZipFileToCreate = files2[k] + ".zip";
                using (ZipFile zip = new ZipFile())
                {
                    try
                    {
                        zip.StatusMessageTextWriter = System.Console.Out;
                        zip.AddDirectory(path7);
                        zip.Save(ZipFileToCreate);
                    }
                    catch (Exception ex6)
                    {
                        MessageBox.Show(ex6.ToString());
                    }
                }
                Directory.Delete(files2[k], true);
            }

            MessageBox.Show("Congratulations! Your all files are moved and zipped successfully");
        }
        private void btnChooseDestPath_Click(object sender, EventArgs e)
        {
            DialogResult result = ChooseDestPath.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtPathMove.Text = ChooseDestPath.SelectedPath;
            }
        }

        private void btnChooseSourcePath_Click(object sender, EventArgs e)
        {
            DialogResult result = ChooseSourcePath.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtPath.Text = ChooseSourcePath.SelectedPath;
            }
        }
    }
}

      
     

MVC Login Page

AppStart-->RouteConfig.cs
            routes.MapRoute(
               name: " ",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "AdminLogin", action = "AdminLogin_Fun", id = UrlParameter.Optional }
           );



Views-->Shared-->_Layout.cshtml
 <link rel="stylesheet" href="@Url.Content("~/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css")">
    <script src="@Url.Content("~/plugins/jQuery/jQuery-2.1.4.min.js")"></script>




 <ul class="sidebar-menu">
                        <li class="header" style="color: White;">Bill Validator</li>
                        <li class=" treeview">
                            <a href="@Url.Action("Dashbord", "Home")">
                                <i class="fa fa-dashboard"></i><span>DASHBORD</span>
                            </a>
                        </li>
                        <li class=" treeview">
                            <a href="@Url.Action("Upload_MObile_Bill_Fun","Upload_Mobile_Bill")">
                                <i class="fa fa-dashboard"></i><span>UPLOAD BILLS</span>

                            </a>
                        </li>





Views-->ViewsStart.cshtml
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}



Views-->ViewsStart.cshtml-->AdminLogin-->AdminLogin_Fun.cshtml
@model Bill_Validator.Models.UserLoginModel

@{
    Layout = null;
}

<link rel="stylesheet" href="@Url.Content("~/assets/bootstrap/css/bootstrap.min.css")">
 <script src="@Url.Content("~/assets/js/jquery-1.11.1.min.js")"></script>

   <div class="form-bottom">


                            @using (@Html.BeginForm("login_action", "AdminLogin"))
                            {
                                <div class="form-group">
                                    <label class="sr-only" for="form-username">Username</label>

                                    @Html.TextBoxFor(m => m.UserId, new { @class = "form-username form-control" })
                                </div>
                                <div class="form-group">
                                    <label class="sr-only" for="form-password">Password</label>

                                    @Html.PasswordFor(m => m.Password, new { @class = "form-username form-control" })

                                </div>
                                <button type="submit" class="btn">Sign in!</button>


                            }

                        </div>

Models-->UserLoginModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bill_Validator.Models
{
    public class UserLoginModel
    {
        public string UserId { get; set; }
        public string Password { get; set; }
    }
}






Controllers-->AdminLoginController.cs
using Bill_Validator.DataAccessLayer;//Data Access Layer NameSpace
using Bill_Validator.Models;// Models class Login.css
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Bill_Validator.Controllers
{
    public class AdminLoginController : Controller
    {
        //
        // GET: /AdminLogin/
        public ActionResult AdminLogin_Fun()
        {
            return View();
        }



        [HttpPost]
        public void login_action(UserLoginModel ur)
        {

            Login l = new Login();

            bool value = l.CreateLogin(ur);

            if (value.Equals(true))
            {
                Response.Redirect(Url.Action("Dashbord", "Home"));
            }
            else
            {
                Response.Redirect(Url.Action("AdminLogin_Fun", "AdminLogin"));

            }
        }



    }
}




DataAccessLayer-->Login.cs
using Bill_Validator.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bill_Validator.DataAccessLayer
{
    public class Login
    {
      
       
        MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=billvalidator;UID=root;PASSWORD=techsoft;");
      
       
        public bool CreateLogin(UserLoginModel data)
        {
            String S = "SELECT * FROM login where username= '" + data.UserId + "' and password='" + data.Password + "'"; ;

            MySqlCommand cmd = new MySqlCommand(S, con);

            con.Open();
            bool status = true;
            MySqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                return status;
            }
            else
            {
                return status = false;

            }

            con.Close();
        }
    }
}