Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, September 29, 2014

Display thaana dates in dhivehi sites.


Here is a small JavaScript snippet which can be used to display date strings in thaana format.

thaanaDates.js

 function thaanaDates(dateObj){   
           this.getLong = function() {  
             return dateObj.getDate() + " " + dateObj.getThaanaMonthName() + " " + dateObj.getFullYear() + " (" + dateObj.getThaanaDayName() + ")";  
           }  
           this.getShort = function() {  
             return dateObj.getDate() + " " + dateObj.getThaanaMonthName() + " " + dateObj.getFullYear();  
           }  
           this.getLongReverse = function() {  
              return dateObj.getFullYear() + " " + dateObj.getThaanaMonthName() + " " + dateObj.getDate() + "، " + dateObj.getThaanaDayName() + "";  
           }  
           this.getDayFirst = function() {  
              return dateObj.getThaanaDayName() + "، " + dateObj.getDate() + " " + dateObj.getThaanaMonthName() + " " + dateObj.getFullYear() + "";  
           }       
 }  
 Date.prototype.getThaanaMonthName = function() {  
           var m = ["ޖަނަވަރީ","ފެބްރުއަރީ","މާރިޗު","އޭޕުރީލް","މޭ","ޖޫން","ޖުލައި","އޯގަސްޓް","ސެޕްޓެމްބަރު","އޮކްޓޯބަރު","ނޮވެމްބަރު","ޑިސެމްބަރު"];            
           return m[this.getMonth()];  
 }   
 Date.prototype.getThaanaDayName = function() {  
           var d = ["އާދީއްތަ","ހޯމަ","އަންގާރަ","ބުދަ","ބުރާސްފަތި","ހުކުރު","ހޮނިހިރު"];  
           return d[this.getDay()];  
 }  


Methods:

  •  getLong: Displays long formatted thaana date string
  •  getShort: Displays date without a day string
  •  getLongReverse: Displays date string with year at the beginning
  •  getDayFirst: Displays date string with day string at the beginning

Simpla Usage:


 document.getElementById("demo").innerHTML = new thaanaDates(new Date).getLong();  

Downloads:

thaanaDates.js
thaanaDates.min.js

Thursday, March 13, 2014

.NET Function to check if a file in use

Here is a .NET Function to use whether a file in system is in use by another process or application before attempting to use the file.

If the file is in use following function will return false.

VB.NET

  1. Public Function FileInUse(ByVal sFile As String) As Boolean
  2. Dim thisFileInUse As Boolean = False
  3. If System.IO.File.Exists(sFile) Then
  4. Try
  5. Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
  6. ' thisFileInUse = False
  7. End Using
  8. Catch
  9. thisFileInUse = True
  10. End Try
  11. End If
  12. Return thisFileInUse
  13. End Function

C#

  1. public bool FileInUse(string sFile)
  2. {
  3. bool thisFileInUse = false;
  4. if (System.IO.File.Exists(sFile)) {
  5. try {
  6. using (System.IO.FileStream f = new System.IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
  7. // thisFileInUse = False
  8. }
  9. } catch {
  10. thisFileInUse = true;
  11. }
  12. }
  13. return thisFileInUse;
  14. }

Wednesday, March 12, 2014

Free PDF Splitter - Nashath Auto PDF Splitter 1.0


This is a FREE Software under GPL 3.0, which splits pdf files on a given folder and saves to another location while leaving  a copy of original file into a different folder.

This standalone tool watches any given folder for PDF files and once a pdf file is created on the folder, it splits file into seperate single page files and save it into a different folder and moves orginals to another folder. This software uses pdftk-server http://www.pdflabs.com/tools/pdftk-server/ to split pdf files.

Download link
http://nashathpdfsplitter.codeplex.com/

Wednesday, October 3, 2012

VB.NET Easy way to write to Text File

Following lines of code is enough to write a string to a text file.

First, import the name space, system.IO

Second, use following code snippet at anywhere in your application which has the requirement to write to a file.

Using sr As StreamWriter = New StreamWriter("myfile.txt", True)
            sr.WriteLine("Hello")

End Using

Explaining the Highlights:
1. "myfile.txt" is the file name you want write to, can include file locations. if the file does not exists in the location, file will be created.
2. True  ,means append to the file if file exist, use false to write new.
3.   sr.WriteLine("Hello") , used to write to the file. 

Wednesday, September 26, 2012

SQL Query: Getting Data by Age Groups from a date column


Recently i was working on a Ballot progress reporting system at my office. for that i have to generate a data set which has number of voters grouped by age group. This can be easily done at application level coding. But i wanted to have SQL query which directly out put these data for me as a SP.

Voting data is collected to this table
 

So here is what my query looks like.


SELECT ages.age_s +Sep.s+ages.age_e as AgeGroup ,COUNT(T)as Count
FROM (SELECT ' - ' AS s) AS Sep
CROSS JOIN
(SELECT '18' AS age_s, '24' AS age_e
UNION ALL
SELECT '25' AS age_s, '34' AS age_e
UNION ALL
SELECT '35' AS age_s, '44' AS age_e
UNION ALL
SELECT '45' AS age_s, '54' AS age_e
UNION ALL
SELECT '55' AS age_s, '64' AS age_e
UNION ALL
SELECT '65' AS age_s, '74' AS age_e
UNION ALL
SELECT '75' AS age_s, '100' AS age_e) AS ages
LEFT OUTER JOIN 

(SELECT ((DATEPART(year, CONVERT (date, GETDATE())
))-(DATEPART(year, dob))) as T from VotingInfo ) AS m
ON T BETWEEN ages.age_s AND age_e 
GROUP by ages.age_s +Sep.s+ages.age_e
ORDER BY ages.age_s +Sep.s+ages.age_e asc


Output of the above query




Explanation:

  1.  'age_s' and 'age_e' is boundary of age groups like 18-24,25-34
  2.  'dob' is the field name where i stored Dob of those who have voted
  3.  'VotingInfo' is the table name from where i collect date
 
Data visualized in the application



Sunday, October 23, 2011

PHP Captcha Class Using Session Variable

Following php class will generate a captcha at runtime using random numbers assigned to session variable and display it as an image.
Captcha generated using this class


// Set the content-type
session_start();


header('Content-Type: image/png');


// Create the image
$im = imagecreatetruecolor(180, 40);


// Create some colors
$white = imagecolorallocate($im, 255, 248, 201);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 135, 85, 70);
imagefilledrectangle($im, 2, 2, 178, 38, $white);


// The text to draw
$text = $_SESSION['secure'];
// Replace path by your own font path
$font = 'nyala.ttf';


// Add some shadow to the text
imagettftext($im, 35, 0, 0, 0, $black, $font, $text);


// Add the text
imagettftext($im, 38, 0, 20, 30, $black, $font, $text);


for ($i = 1; $i <= 150; $i++) {
    $x1=rand (1,180);
$y1=rand (1,180);
$x2=rand (1,180);
$y2=rand (1,180);
imageline($im ,$x1,$y1,$x2,$y2, $black);
}
$rey2 = imagecolorallocate($im, 255, 248, 201);


for ($i = 1; $i <= 30; $i++) {
    $x1=rand (1,180);
$y1=rand (1,180);
$x2=rand (1,180);
$y2=rand (1,180);
imageline($im ,$x1,$y1,$x2,$y2, $rey2);
}
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>



Save the above file with the name generate.php or any other name you like.


How to call this Class 
In the page you want add this captcha,add following code to header



session_start();
if (!isset($_POST['secure'])) {
$_SESSION['secure'] =rand(100000, 999999);
}

and in img tag src call to
src="generate.php"




Tuesday, February 22, 2011

VB.Net Send Email With Attachment (SMTP)

'Send Mail Class


Imports Microsoft.VisualBasic
Imports System.Net.Mail
Imports System.Text


Public Class SendEmail
    Dim smtpCredentials As New Net.NetworkCredential("username", "password")
    Public Sub SendEmailMessage(ByVal strFrom As String, ByVal strTo() _
    As String, ByVal strSubject _
    As String, ByVal strMessage _
    As String, ByVal fileList() As String)
        'This procedure takes string array parameters for multiple recipients and files
        Try
            For Each item As String In strTo
                'For each to address create a mail message
                Dim MailMsg As New MailMessage(New MailAddress(strFrom.Trim()), New MailAddress(item))
                MailMsg.BodyEncoding = Encoding.Default
                MailMsg.Subject = strSubject.Trim()
                MailMsg.Body = strMessage.Trim() & vbCrLf
                MailMsg.Priority = MailPriority.High
                MailMsg.IsBodyHtml = True


                'attach each file attachment
                For Each strfile As String In fileList
                    If Not strfile = "" Then
                        Dim MsgAttach As New Attachment(strfile)
                        MailMsg.Attachments.Add(MsgAttach)
                    End If
                Next


                'Smtpclient to send the mail message
                Dim SmtpMail As New SmtpClient
                SmtpMail.UseDefaultCredentials = False
                SmtpMail.Host = "hostname"
                SmtpMail.EnableSsl = True
                SmtpMail.Credentials = smtpCredentials
                SmtpMail.Send(MailMsg)
            Next
            MessageBox.Show("Success")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub


    Public Sub SendEmailMessage(ByVal strFrom As String, ByVal strTo _
    As String, ByVal strSubject _
    As String, ByVal strMessage _
    As String, ByVal file As String)
        'This procedure overrides the first procedure and accepts a single
        'string for the recipient and file attachement 
        Try
            Dim MailMsg As New MailMessage(New MailAddress(strFrom.Trim()), New MailAddress(strTo))
            MailMsg.BodyEncoding = Encoding.Default
            MailMsg.Subject = strSubject.Trim()
            MailMsg.Body = strMessage.Trim() & vbCrLf
            MailMsg.Priority = MailPriority.High
            MailMsg.IsBodyHtml = True


            If Not file = "" Then
                Dim MsgAttach As New Attachment(file)
                MailMsg.Attachments.Add(MsgAttach)
            End If


            'Smtpclient to send the mail message
            Dim SmtpMail As New SmtpClient
            SmtpMail.UseDefaultCredentials = False
            SmtpMail.Host = "mail.elections.gov.mv"
            SmtpMail.Credentials = smtpCredentials
            SmtpMail.Send(MailMsg)
            MessageBox.Show("List has been Successfully mailed to Elections Commission", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class




'Send Mail Button Code



Private Sub btnSendEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click
        Dim SendEmail As New SendEmail
        Dim SendTo As String
        Dim FileAttach As String = Nothing
        Dim strSubject As String
        Dim strMessage As String




        SendTo = "to"


        FileAttach = "location of the Attachment"


        strSubject = "Subject"


        strMessage = "Message" 'The body encoding is set to HTML 


        SendEmail.SendEmailMessage("frommail", SendTo, strSubject, strMessage, FileAttach)
    End Sub


    Private Sub cmbConsit_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbConsit.SelectedIndexChanged
        values(cmbConsit.SelectedItem)
    End Sub


Thursday, September 9, 2010

Selecting word by right clicking richtextbox vb.net

Recently I've searched internet to find a way to select a word in richtextbox by right clicking the word. But ended up with nothing. May be I've not used right key words to search. Anyways here is what i did by referring to the resource. I hope these would be useful to sum1 like me.

Use these line of codes at mouse down event of richtextbox.


Private Sub rtbInput_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles rtbInput.MouseDown



        ' Getting the word under the mouse clicked loaction
        If e.Button = MouseButtons.Right Then
            Dim CharIndex As Int32
            Dim StartPos As Int32
            Dim EndPos As Int32

            'location of mouse clicked
            CharIndex = rtbInput.GetCharIndexFromPosition(New Point(e.X, e.Y))
            'Locating the end point of the selections
            EndPos = rtbInput.Text.IndexOf(" ", CharIndex)
            'Locating the start point of the selection
            StartPos = rtbInput.Text.LastIndexOf(" ", CharIndex)

            'Checking if the mouse clicked on word 
            If EndPos = -1 Then
                EndPos = 0
            End If
            If StartPos = -1 Then
                StartPos = 0
            End If
            If StartPos > EndPos Then
                Exit Sub
            End If
            'selecting the word under the clicked location
            CharIndex -= StartPos
            rtbInput.Select(StartPos, EndPos - StartPos)
        End If
    End Sub