Tuesday, 30 April 2019

Datepicker Seleted Date event in IOS mobile

DatePicker correctly work in Android while selecting date. Date_Selected event trigger when click on done button.

While in IOS mobile it's trigger everytime we change date or month or year.
if you want to trigger event only when click on Done button from Datepicker control.
Instead of Date_Selected event call Date_Unfocused event. It will work correctly


            if (Device.OS == TargetPlatform.iOS)
            {
                dtPicker.Unfocused += DtPicker_Unfocused;
            }
            else

            {
                dtPicker.DateSelected += DtPicker_DateSelected;
            }

Thursday, 29 November 2018

Open Google Map URL in iphone and Android using Xamarian

Open Google map url in Android phone.

  var uri = new Uri("https://www.google.com/maps/place/" + CustomerAddress.Replace("<br/>", ""));
                    Device.OpenUri(uri);


For android phone it is easy to open map. But for IOS device the code is different. First check if location service is turned on or off. The location service in iphone should be on.

Below is the code for IOS

   var name = Uri.EscapeUriString(CustomerAddress.Replace("<br/>", "").Replace("&", "and")); // var name = Uri.EscapeUriString(place.Name);
                    var request = Device.OnPlatform(string.Format("http://maps.apple.com/maps?q={0}", name.Replace(' ', '+')), null, null);
                    Device.OpenUri(new Uri(request));


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

    }

Thursday, 14 September 2017

Zoom in, out and print the image

Imageviewer is very good package for zoom image. you can install it from Nuget package

npm install imageviewer



It Provides functionality like to zoom in , Zoom Out, Rotate the image.  you can even play in slide view. but does not provide print functionality.

To implement Print functionality requires some changes in Viewer.js and viewer.css



Changes of Viewer.Js

1) In Viewer.TEMPLATE  add one li after flip-vertical.


 '<li class="viewer-flip-vertical" data-action="flip-vertical"></li>' +
            '<li class="viewer-print" data-action="print"></li>' +

2) On click: function (e)  Add another case print below flip-vertical

               case 'flip-vertical':
                    this.scaleY(-image.scaleY || -1);
                    break;

                case 'print':
                    this.printDiv();
               
                    break;

3) Add function in js.

        printDiv: function()
        {
            $('.viewer-canvas').print();
        },


Viewer.css change

.viewer-print {
    background: url(/Content/images/print.png) no-repeat;
    background-size: 11px !important;
    background-position: center;
}

.viewer-toolbar {
 width: 315px;
}


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