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

Thursday, 14 June 2018

Read word or doc file without installing office

To Read word file use NPOI.dll. Install from Nuget and add reference into your project. below is the method for that.


 try
                        {
                            XWPFDocument wDoc = new XWPFDocument();
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                wDoc = new XWPFDocument(fs);
                            }

                            foreach (XWPFParagraph prg in wDoc.Paragraphs)
                            {
                                resumeText = resumeText + prg.Text;
                            }
                            resumeText = resumeText.ToLower();
                        }
                        catch
                        {


                        }

if still word is not supported by this dll means getting error while reading document then write below code.  in that i have used DocumentFormat.OpenXml.dll. add package from Nuget.

 if (String.IsNullOrEmpty(resumeText))
                        {
                            resumeText = ReadWordDocument(fileName);
                        }


 public string ReadWordDocument(string filepath)
    {
        WordprocessingDocument package = null;
        package = WordprocessingDocument.Open(filepath, true);
     
        StringBuilder sb = new StringBuilder();
        OpenXmlElement element = package.MainDocumentPart.Document.Body;
        if (element == null)
        {
            return string.Empty;
        }

        sb.Append(GetPlainText(element));
        return sb.ToString();
    }

  public string GetPlainText(OpenXmlElement element)
    {
        StringBuilder PlainTextInWord = new StringBuilder();
        foreach (OpenXmlElement section in element.Elements())
        {
            switch (section.LocalName)
            {
                // Text
                case "t":
                    PlainTextInWord.Append(section.InnerText);
                    break;

                case "cr":                          // Carriage return
                case "br":                          // Page break
                    PlainTextInWord.Append(Environment.NewLine);
                    break;

                // Tab
                case "tab":
                    PlainTextInWord.Append("\t");
                    break;

                // Paragraph
                case "p":
                    PlainTextInWord.Append(GetPlainText(section));
                    PlainTextInWord.AppendLine(Environment.NewLine);
                    break;

                default:
                    PlainTextInWord.Append(GetPlainText(section));
                    break;
            }
        }

        return PlainTextInWord.ToString();
    }

Get Chrome and internet explorer browser history

Below is the code to get browser history.

Chrome:

  public class HistoryItem
    {
        public string URL { get; set; }

        public string Title { get; set; }

        public DateTime VisitedTime { get; set; }
    }
    List<HistoryItem> allHistoryItems = new List<HistoryItem>();

 public void GetChromeHistory()
    {
        allHistoryItems = new List<HistoryItem>();
        string chromeHistoryFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default\History";
        if (File.Exists(chromeHistoryFile))
        {

            string filePath = System.Web.Hosting.HostingEnvironment.MapPath("/History/");
            string fileid = "History_" + Guid.NewGuid();
            newFilePath = filePath + fileid;
            File.Copy(chromeHistoryFile, newFilePath);
         
            using (SQLiteConnection connection = new SQLiteConnection
                 ("Data Source=" + newFilePath + ";Version=3;New=False;Compress=True;"))
            {

                DataSet dataset = new DataSet();

                SQLiteDataAdapter adapter = new SQLiteDataAdapter
                ("select  * from urls order by last_visit_time desc", connection);
                adapter.Fill(dataset);
                if (dataset != null && dataset.Tables.Count > 0 & dataset.Tables[0] != null)
                {
                    DataTable dt = dataset.Tables[0];


                    foreach (DataRow historyRow in dt.Rows)
                    {
                        HistoryItem historyItem = new HistoryItem
                        {
                            URL = Convert.ToString(historyRow["url"]),
                            Title = Convert.ToString(historyRow["title"])
                        };

                        // Chrome stores time elapsed since Jan 1, 1601 (UTC format) in microseconds
                        long utcMicroSeconds = Convert.ToInt64(historyRow["last_visit_time"]);

                        // Windows file time UTC is in nanoseconds, so multiplying by 10
                        DateTime gmtTime = DateTime.FromFileTimeUtc(10 * utcMicroSeconds);

                        // Converting to local time
                        DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(gmtTime, TimeZoneInfo.Local);
                        historyItem.VisitedTime = localTime;

                        allHistoryItems.Add(historyItem);
                    }
                }
            }
        }


        gridChrome.DataSource = allHistoryItems;
        gridChrome.DataBind();
        try
        {
            if (File.Exists(newFilePath))
            {
                File.Delete(newFilePath);
            }
        }
        catch
        {
        }
    }


Internet Explorer:

 public void GetInternetExplorerHistory()
    {

        allHistoryItems = new List<HistoryItem>();

        // Initiate main object
        UrlHistoryWrapperClass urlhistory = new UrlHistoryWrapperClass();


        // Enumerate URLs in History
        UrlHistoryWrapperClass.STATURLEnumerator enumerator =

                                           urlhistory.GetEnumerator();

        // Iterate through the enumeration
        while (enumerator.MoveNext())
        {
            // Obtain URL and Title

            string url = enumerator.Current.URL.Replace('\'', ' ');
            if (url.StartsWith("http"))
            {
                // In the title, eliminate single quotes to avoid confusion
                string title = string.IsNullOrEmpty(enumerator.Current.Title) ? "" : enumerator.Current.Title.Replace('\'', ' ');

                // Create new entry
                HistoryItem historyItem = new HistoryItem
                {
                    URL = url,
                    Title = title
                };
                // Add entry to list
                allHistoryItems.Add(historyItem);
            }
        }

        // Optional
        enumerator.Reset();

        // Clear URL History
        // urlhistory.ClearHistory();

        gridIE.DataSource = allHistoryItems;
        gridIE.DataBind();

    }

Tuesday, 13 December 2016

Read email of outlook of pop3 server

when you read email if your server is pop3 server.


using (Pop3Client client = new Pop3Client())
                {

                    // Connect to the server
                    client.Connect(EmailServer, Convert.ToInt32(Port), true);

                    // Authenticate ourselves towards the server
                    client.Authenticate(UserName, Password);

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    List<Email> Emails = new List<Email>();
                    int counter = 0;
                    for (int i = messageCount; i >= 1; i--)
                    {
                        DateTime currentDate = DateTime.Now.AddDays(-2).Date;

                        Message message = client.GetMessage(i);
                        Email email = new Email()
                        {
                            MessageNumber = i,
                            Subject = message.Headers.Subject,
                            DateSent = message.Headers.Date,
                            From = message.Headers.From.Address,
                        };

                     
                            MessagePart body = message.FindFirstHtmlVersion();
                            if (body != null)
                            {
                                email.Body = body.GetBodyAsText();
                            }
                            else
                            {
                                body = message.FindFirstPlainTextVersion();
                                if (body != null)
                                {
                                    email.Body = body.GetBodyAsText();
                                }
                            }
                            List<MessagePart> attachments = message.FindAllAttachments();

                            foreach (MessagePart attachment in attachments)
                            {
                                email.Attachments.Add(new Attachment
                                {
                                    FileName = attachment.FileName,
                                    ContentType = attachment.ContentType.MediaType,
                                    Content = attachment.Body
                                });
                                string filePath = mailbox + "\\" + attachment.FileName;
                                if (Path.GetExtension(filePath) == ".xlsx" || Path.GetExtension(filePath) == ".xls")
                                {
                                    FileStream Stream = new FileStream(filePath, FileMode.Create);
                                    Stream.Position = 0;
                                    BinaryWriter BinaryStream = new BinaryWriter(Stream);
                                    BinaryStream.Write(attachment.Body);
                                    Stream.Close();
                                    BinaryStream.Close();
                                }
                            }


                            Emails.Add(email);
                        }
                        counter++;
                        if (currentDate >= Convert.ToDateTime(email.DateSent).Date)
                        {
                            break;
                        }
                 

Read Office365 Outlook email also save attachement

I have one requirement to read office365 email and it is not possible using pop3Client so i have used Microsoft.Exchange.WebServices


Below are the configuration add into app.config file.
 <add key="Username" value=""/>
    <add key="Password" value=""/>
    <add key="Domain" value=""/>
    <add key="EWSUrl" value="https://outlook.office365.com/EWS/Exchange.asmx"/>
    <add key="SharedMailBox" value=""/>


Below are the codes 



Services.cs Class

   public static ExchangeService ConnectToService()
        {
            // We use this to get the target Exchange version. 
            UserData data = new UserData();
            ExchangeService service = new ExchangeService(data.Version);
            service.Url = new Uri(Convert.ToString(ConfigurationManager.AppSettings["EWSUrl"]));
            try
            {
                AuthenticationHelper.Authenticate(data.EmailAddress, data.Password, ref service);
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(ex, AppSetting.ErrorFilePath);
            }
            return service;
        }



In Program.cs call first call ConnectToService function then call below  GetMailsFromServices function.


 public static ExchangeService GetMailsFromServices(ExchangeService service)
        {
            try
            {
                string curpath = Directory.GetCurrentDirectory();
                string mailbox = String.Format("{0}\\inbox", curpath);

                int offset = 0;
                int pageSize = 50;
              
                List<EmailMessage> emails = new List<EmailMessage>();
                ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);

                view.PropertySet = new PropertySet(ItemSchema.Flag, ItemSchema.Id, ItemSchema.Categories, ItemSchema.Attachments, FolderSchema.DisplayName);
                FolderView Folderview = new FolderView(int.MaxValue);

             
                Mailbox sharedMailbox = new Mailbox(ConfigurationManager.AppSettings["SharedMailBox"]);
                FindFoldersResults findResultsFolder = service.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, sharedMailbox), Folderview);
                foreach (Microsoft.Exchange.WebServices.Data.Folder folder in findResultsFolder.Folders)
                {
                    // Here we are using spacific forlder to manipulate 
                    // On the mailbox there is a rule to move all mail to "UnprocessedEmails" and processed mail to inbox 
                    if (folder.DisplayName == "Inbox")
                    {
                        ItemView itemView = new ItemView(int.MaxValue);
                        FindItemsResults<Item> searchResults = service.FindItems(folder.Id, itemView);

                   
                            foreach (var item in searchResults.Items)
                            {
                                // get the subject 
                                var senderSubject = item.Subject;
                                var fromAddress = ((EmailMessage)item).From.Address;
                                DateTime receviedDate = item.DateTimeReceived;
                                DateTime currentDate = DateTime.Now.AddDays(LastDaysToReadEmail).Date;

                                if (!string.IsNullOrWhiteSpace(senderSubject))
                                {
                                    if (senderSubject.IndexOf(EmailSubject) > 0)
                                   {
                                        emails.Add((EmailMessage)item);
                                        item.Load();
                                        if (item.HasAttachments)
                                        {
                                            foreach (var excelattachment in item.Attachments)
                                            {

                                                FileAttachment fileAttachment = excelattachment as FileAttachment;

                                                string fileExtension = Path.GetExtension(((Microsoft.Exchange.WebServices.Data.Attachment)(fileAttachment)).Name);
                                                string fileName = Path.GetFileName(((Microsoft.Exchange.WebServices.Data.Attachment)(fileAttachment)).Name);
                                                string fullPath = mailbox + "\\" + fileName;
                                                if (fileExtension == ".xls" || fileExtension == ".xlsx")
                                                {
                                                    if (!Directory.Exists(mailbox))
                                                    {
                                                        Directory.CreateDirectory(mailbox);
                                                    }

                                                    fileAttachment.Load(fullPath);
                                                    
                                                }
                                            }
                                        }
                                    }
                                }

                                if (currentDate >= receviedDate.Date)
                                {
                                    break;
                                }
                            }
                        
              
                      
                    }
                }


                return service;

            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(ex, AppSetting.ErrorFilePath);
                return null;
            }
        }

Let me know if want more details about it.

Monday, 26 September 2016

CRUD Operation using datatable.js in asp.net mvc

Below is the description about CRUD Operation using datatable.js in asp.net mvc. below is the step by step code for that. 


View Changes


Add below style sheet and javascript in view.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/> // bootstrap
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css"/> // dataTables
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css"/> // dataTables.buttons
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css"/> // dataTables.select
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css"/> // dataTables.responsive

<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> // jQuery
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> // bootstrap
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script> // dataTables
<script src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script> // dataTables.buttons
<script src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script> // dataTables.select
<script src="https://cdn.datatables.net/responsive/2.0.2/js/dataTables.responsive.min.js"></script>
<script src="js/altEditor/dataTables.altEditor.free.js"></script> // dataTables.altEditor

script to call datatable


<script type="text/javascript">

$(document).ready(function () {

$('#tblCompanylist').dataTable({
"sPaginationType": "full_numbers",
"bPaginate": true,
"iDisplayLength": 25,
"scrollX": true,
responsive: true,
altEditor: true,
dom: 'Bfrtip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [{
text: 'Add',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Edit',
name: 'edit' // do not change name
}]
});
});

</script>


Html changes


<div id="divCompanylist" style="padding-top: 60px;">
<table id="tblCompanylist" class="display dataTable" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Customer Number</th>
<th>Website Url</th>
<th>Logo File Name</th>
<th>Company Name</th>
<th>Street</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{

<tr id="@item.CompanyId">
<td>@item.CompanyId</td>
<td>@item.CustomerNumber</td>
<td>@item.WebsiteUrl</td>
<td>@item.LogoFileName</td>
<td>@item.CompanyName</td>
<td>@item.Street</td>
<td>@item.City</td>
<td>@item.State</td>
<td>@item.ZipCode</td>
</tr>
}
</tbody>
</table>
</div>

Controller changes 
Add below methods in controller
public void UpdateData(int id, int CustomerNumber, string WebsiteUrl, string LogoFileName, string CompanyName, string Street, string City, string State,
string ZipCode
)
{
CompanyDAO _companyInfo = new CompanyDAO();
var companies = _companyInfo.GetAllCompanyInformation();

CompanyInformation companyRow = new CompanyInformation();
companyRow.CompanyId = id;
companyRow.CustomerNumber = CustomerNumber.ToString();
companyRow.WebsiteUrl = WebsiteUrl;
companyRow.LogoFileName = LogoFileName;
companyRow.CompanyName = CompanyName;
companyRow.Street = Street;
companyRow.City = City;
companyRow.State = State;
companyRow.ZipCode = ZipCode;
companyRow.CompanyPhone = CompanyPhone;
companyRow.IsActive = true;

_companyInfo.SaveCompany(companyRow, 1);
}

public void AddData(int id, int CustomerNumber, string WebsiteUrl, string LogoFileName, string CompanyName, string Street, string City, string State,
string ZipCode, string CompanyPhone)
{
CompanyDAO _companyInfo = new CompanyDAO();
var companies = _companyInfo.GetAllCompanyInformation();

CompanyInformation companyRow = new CompanyInformation();
companyRow.CustomerNumber = CustomerNumber.ToString();
companyRow.WebsiteUrl = WebsiteUrl;
companyRow.LogoFileName = LogoFileName;
companyRow.CompanyName = CompanyName;
companyRow.Street = Street;
companyRow.City = City;
companyRow.State = State;
companyRow.ZipCode = ZipCode;
companyRow.CompanyPhone = CompanyPhone;
_companyInfo.SaveCompany(companyRow, 0);
}


download dataTables.altEditor.free.js from internet if do not find send me email. 


The main changes are in dataTables.altEditor.free.js to make ajax call for add and update.

On click of add button _addRowData function is called so create ajax call or any other extra operation you want to do you can change here. In this function I have added code of validation and save into database code.



if (data[1] == "") {
alert("Please enter customer number");
return false;
}
if (data[2] == "") {
alert("Please enter website url");
return false;
}
if (data[4] == "") {
alert("Please enter company name");
return false;
}


$.ajax({
url: "/company/AddData",
type: "GET",
data: {
id: data[0], CustomerNumber: data[1], WebsiteUrl: data[2], LogoFileName: data[3], CompanyName: data[4],
Street: data[5], City: data[6], State: data[7], ZipCode: data[8], CompanyPhone: data[9]
},
success: function (response) {

$('#altEditor-modal .modal-body .alert').remove();
var message = '<div class="alert alert-success" role="alert">\
<strong>Success!</strong> This record has been added.\
</div>';

$('#altEditor-modal .modal-body').append(message);
}
});

same thing I did for edit. For edit _editRowData function is called.


if (data[1] == "")
{
alert("Please enter customer number");
return false;
}
if (data[2] == "")
{
alert("Please enter website url");
return false;
}
if (data[4] == "") {
alert("Please enter company name");
return false;
}

$.ajax({
url: "/company/UpdateData",
type: "GET",
data: { id: data[0], CustomerNumber: data[1], WebsiteUrl: data[2], LogoFileName: data[3], CompanyName: data[4],
Street: data[5], City: data[6], State: data[7],ZipCode: data[8], CompanyPhone: data[9] },
success: function (response) {


$('#altEditor-modal .modal-body .alert').remove();
var message = '<div class="alert alert-success" role="alert">\
<strong>Success!</strong> This record has been updated.\
</div>';

$('#altEditor-modal .modal-body').append(message);
}
});

Tuesday, 21 June 2016

The request was aborted: Could not create SSL/TLS secure channel.

If you got the error like this The request was aborted: Could not create SSL/TLS secure channel when you want to get response from HttpWebrequest object.

Here is simple solution just put below line before getting httpWebResponse.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

if TLS 1.2 is not working then you can also write down as below.

   ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
            ServicePointManager.Expect100Continue = true;