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

Monday, 12 September 2016

convert DTS Package to SSIS

Go to SQL Server 2008 R2 from Programs. Open Business Intelliegence Development studio.

Create new Integration service project.

In Solution explorer go to SSIS Package folder. Right click on Migrate DTS Package.

In pop up box from Source dropdown select structured storage file

then browse your dts package. That's it.

Tuesday, 9 August 2016

Read Google Spreadsheet thorugh Google Sheet API

To read excel sheet follow the below link.

https://developers.google.com/sheets/quickstart/dotnet


Implement olark with google tag manager

Follow the step as per below link

https://www.olark.com/help/google-tag-manager

After then in your page add below google tag manager code.

your GTM-Code will be the code which is generated when you follow the steps of above link.

  <!-- Google Tag Manager -->

    <noscript>
        <iframe src="//www.googletagmanager.com/ns.html?id=GTM-Code"
                height="0" width="0" style="display:none;visibility:hidden"></iframe>
    </noscript>
    <script>
        (function (w, d, s, l, i) {
            w[l] = w[l] || []; w[l].push({
                'gtm.start':
                new Date().getTime(), event: 'gtm.js'
            }); var f = d.getElementsByTagName(s)[0],
            j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
            '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
        })(window, document, 'script', 'dataLayer', 'GTM-Code');</script>


    <!-- End Google Tag Manager -->

Bleow is sample screeen of google tag manager account your GTM code is at on the top at right side.


No need to add olark code in your page.

When you follow the steps of above link ask for Site ID in custom HTML. In that case you have to create your olark account after then it will provide you Site Id.

if popup of chat still  not come then check the checkbox of "send offline message" in Settings -> Behaviour & Text




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;

Monday, 16 May 2016

Add Custom output caching on listing page in asp.net mvc



Add below attribute on controller's method.

[OutputCache(VaryByParam = "None", VaryByCustom = "Host", Duration = 14400)]
public ActionResult Index(string category)

Add below method in gobal.asax file


        public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (custom == "Host")
            {
                string sCategory = "";
             

                if (!string.IsNullOrEmpty(HttpUtility.ParseQueryString(context.Request.Url.ToString()).Get("CategoryName")))
                {
                    sCategory = HttpUtility.ParseQueryString(context.Request.Url.ToString()).Get("CategoryName");
                }
           

                return context.Request.Url.Host + context.Request.Url.Port + sCategory ;
            }
            return String.Empty;
        }

Tuesday, 10 May 2016

display 360 view of image using arqspin api call


string requesturl = "http://api.arqspin.com/nodeapi/search/"ArqspinAPIKey"?query=341;

this request send response like below

{"error":0,"spins":[{"shortid":"2g9yw634atmb5","title":
"341","caption":"","created_at":"2015-09-02T21:11:49.000Z",
"thumbnail":"http://spins0.arqspin.com/2g9yw634atmb5/thumbnail.jpg"}]}

create url using shortid in order to display in 360 view form

var resizeurl  = "//spins0.arqspin.com/iframe.html?spin=" + Obj360Image["spins"][0]["shortid"].ToString() + "&is=-0.16"


add above url in iframe src

<iframe style='border:solid 2px #ddd;' src='" + resizeurl + "' width=350 height=350></iframe>




below are the reference link

https://arqspin.com/seamlessly-integrate-spins-using-the-arqspin-query-api/

Open Model Popup using jquery


first add below js and css into your page.


1) jquery-{version}.js
2) bootstrap-model.js
3) bootstrap-model.css
4 ) bottstrap.min.css

Add below html code into your page.

   <div class="popupindex modal" id="mdProcesserror" style="top: 46% !important; margin-top: -281px;">
        <div class="modal-content" style="width: 169%; margin-left: -40%; ">
            <a href="#" data-dismiss="modal" class="popupmodel_close" onclick="resetModelPopUp()"> </a>
            <div class="modal-body">
                <div id="ProcesserrorBody">
                  Content Of Body
                </div>
            </div>

        </div>
    </div>


Add below styles


.popupindex.modal {
    width: 595px;
}
.popupmodel_close {
    position: absolute;
    top: -15px;
    right: -15px;
    width: 30px;
    height: 30px;
    background: transparent url("../../../content/images/close.png") -40px 0px;
    cursor: pointer;
    z-index: 1103;
}

to open model popup when click on link button

  <a href="#" onclick="javascript: $('#mdProcesserror').modal();">Model Popup</a>