Showing posts with label MVC. Show all posts
Showing posts with label MVC. 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();
    }

Friday, 8 September 2017

HandsonTable Create Anchor tag dynamically


var dataResult = dataResponse.Items;

dataResponse.Items is your resultset.

If you want to set anchor tag and redirect to any other page on click of view.




   for (var i = 0; i < dataResult.length; i++) {
                         
                            dataResult[i].View = "<a onClick=' RedirectToMaintenancePage(" + dataResult[i].WarehouseNumber + "," + dataResult[i].Ordered + "," + dataResult[i].Received + ",\"" + dataResult[i].PONumber + "\",\"" + dataResult[i].PartNumber + "\",\"" + dataResult[i].Make + "\" )'>View</a>";
                       
                        }

 var hotElement = document.querySelector('#hot');

                        var hotSettings = {
                            data: dataResult,
                            columns: [
                                 { data: "View", renderer: "html", editor: false },
                                { data: 'WarehouseNumber', type: 'numeric' },
                                { data: 'PONumber', type: 'text' },
                                { data: 'Ordered', type: 'numeric' },
                                { data: 'Received', type: 'numeric' },
                                { data: 'BackOrdered', type: 'numeric' },
                                { data: 'Make', type: 'text' },
                                { data: 'PartNumber', type: 'text' },
                                { data: 'DateEntered', type: 'date', dateFormat: 'MM/DD/YYYY' },
                                { data: 'DateReceived', type: 'date', dateFormat: 'MM/DD/YYYY' }
                             
                            ],
                            stretchH: 'all',
                            autoWrapRow: true,
                            //height: 342,
                            height: height,
                            colHeaders: [
                                '',
                                'Whse',
                                'PO',
                                'Ordered',
                                'Received',
                                'Back Order',
                                'Make',
                                'Part',                            
                                'Date Entered',
                                'Date Received',
                             
                            ]
                        };

                        hotInquiry = new Handsontable(hotElement, hotSettings);

Thursday, 2 March 2017

Attach images in email body in asp.net



in email body if you want to attach images which is in your images folder. Like in signautre we put
facebook, twitter link with icon then below is the code.


  bool isMailSent = false;
            string SmtpHost = Convert.ToString(ConfigurationManager.AppSettings["smtpClient"]);
            string SmtpUserName = Convert.ToString(ConfigurationManager.AppSettings["MailerUser"]);
            string SmtpPassword = Convert.ToString(ConfigurationManager.AppSettings["MailerPassword"]);
       
            SmtpClient mailClient = new SmtpClient(SmtpHost);
            mailClient.Credentials = new System.Net.NetworkCredential(SmtpUserName, SmtpPassword);

            MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;
       
             msg.To.Add(new MailAddressAppSetting.ToEmailAddress
            msg.From = new MailAddress(AppSetting.FromEmailAddress);
             msg.Subject = "Test Attach image";


            StringBuilder sb = new StringBuilder();


            string Str = "<html>";
            Str += "<head>";
            Str += "<title></title>";
            Str += "</head>";
            Str += "<body>";
            Str += "<table border=0 width=95% cellpadding=0 cellspacing=0>";
            Str += "<tr>";
            Str += "<td> Good Day </td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td>Please feel free to contact me with any questions, comments or concerns. </td>";
            Str += "</tr>";

            Str += "<tr>";
            Str += "<td><b>Thanks,</b></td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td><b>Marry</b></td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td>Mary@gmail.com</td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td>&nbsp;</td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td><img src=cid:CompanyLogo></td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td>&nbsp;</td>";
            Str += "</tr>";
            Str += "<tr>";
            Str += "<td><a href='#'><img src=cid:facebook></a><a href='#'><img src=cid:twitter></a> <a href='#'><img src=cid:linkedin> </a></td>";
            Str += "</tr>";


            Str += "</table>";
            Str += "</body>";
            Str += "</html>";

            string Body = Str;

            msg.Priority = MailPriority.Normal;
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

            string imgFile = AppDomain.CurrentDomain.BaseDirectory + "images\\image001.png";
            LinkedResource inline = new LinkedResource(imgFile);
            inline.ContentId = "CompanyLogo";
            htmlView.LinkedResources.Add(inline);

            imgFile = AppDomain.CurrentDomain.BaseDirectory + "images\\facebook.gif";
            inline = new LinkedResource(imgFile);
            inline.ContentId = "facebook";
            htmlView.LinkedResources.Add(inline);

            imgFile = AppDomain.CurrentDomain.BaseDirectory + "images\\twitter.gif";
            inline = new LinkedResource(imgFile);
            inline.ContentId = "twitter";
            htmlView.LinkedResources.Add(inline);

            imgFile = AppDomain.CurrentDomain.BaseDirectory + "images\\linkedin.gif";
            inline = new LinkedResource(imgFile);
            inline.ContentId = "linkedin";
            htmlView.LinkedResources.Add(inline);


            msg.AlternateViews.Add(htmlView);

            if (fileList != null)
            {
                foreach (var item in fileList)
                {
                    Attachment att = new Attachment(item);
                    msg.Attachments.Add(att);
                }
            }

            try
            {
                mailClient.Send(msg);

                isMailSent = true;
            }
            catch (Exception ex)
            {
           
            }


     

Monday, 30 January 2017

Stop Recommended videos and Thumbnail images in embed youtube video

If you want to stop recommended videos after finishing video then you need to add one attribute link in embed youtube url.

to embed youtube video in code below is link to display.

https://www.youtube.com/embed/"+ youtubevideoid +"

now stop recommended videos just add rel=0 in above link.

https://www.youtube.com/embed/" + youtubevideoid + "?rel=0

now if you want to take thumbnail image of respected video then below is the link.

https://img.youtube.com/vi/" + youtubevideoid + "/2.jpg

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