Thursday, June 20, 2013

Get Byte Size in MB Using C# Windows Application


CREATE FUNCTION

static double ConvertBytesToMegabytes(long bytes)
{
            return (bytes / 1024f) / 1024f;
}

Write This Code In Page Load Event

// Now convert to a string in megabytes.
string s = ConvertBytesToMegabytes(6955008).ToString("0.00");

// Convert bytes to megabytes.
MessageBox.Show(s + " MB");

Thursday, June 13, 2013

How to get Size in KB, MB, GB, TB, PB, EB, Bytes In C# Windows Application


Create Static Function

static String BytesToString(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
            if (byteCount == 0)
                return "0" + suf[0];
            long bytes = byteCount;
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 2);
            return (Math.Sign(byteCount) * num).ToString() + suf[place];
        }

Write in Any Place Like This

private void Test_Load(object sender, EventArgs e)
        {
            MessageBox.Show(BytesToString(2000000).ToString());
        }

Tuesday, June 11, 2013

How to Update Sequence ol LI Tag Using Jquery & Update Sequence in DataBase

-- In Repeter Give id to ul #mnu

<asp:Repeater runat="server" ID="Repeater1">
    <HeaderTemplate>
        <ul id="mnu">
            <li>
                <label>Name</label>
            </li>
    </HeaderTemplate>
    <ItemTemplate>
        <li id="<%#((DataRowView)Container.DataItem)["PrimeryKeyID Field Gose Here"]%>">
            <label>
                <%#((DataRowView)Container.DataItem)["Name"]%></b>
            </label>
        </li>
    </ItemTemplate>
    <FooterTemplate>
        </ul>
    </FooterTemplate>

-- Now Create Store Procedure

-- Add Sequence Field in Table As Int Data Type

CREATE PROCEDURE [dbo].[uspTest_UpdateSequence]
    @Sequence nVarchar(max)       
AS       
BEGIN       
       
 SET NOCOUNT ON;       
 Declare @rowID  int,       
   @sequenceFatch int        
         
 DECLARE Menu_cursor CURSOR FOR        
 SELECT * FROM dbo.split(@Sequence,',')         
       
 OPEN Menu_cursor;       
       
 FETCH NEXT FROM Menu_cursor INTO @rowID, @sequenceFatch;       
       
 WHILE @@FETCH_STATUS = 0       
 BEGIN       
 print @rowID     
  print @sequenceFatch     
  UPDATE TableName SET Sequence=@sequenceFatch WHERE Primary Key ID Gose Here = @rowID
  FETCH NEXT FROM Menu_cursor INTO @rowID, @sequenceFatch;       
       
 END--while       
 CLOSE Menu_cursor;       
 DEALLOCATE Menu_cursor;       
       
END

-- Call Store Procedure and Create WebMethod in .aspx Page

-- Add this Namespace for [using System.Web.Services;] WebMethod

[WebMethod(EnableSession = true)]
    public static void UpdateSeq(string newMethQ)
    {
    -- Call Store Procedure as Update Data
    UpdateSequence(newMethQ);
    }

-- Add This Script For Update Sequence

<script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#mnu").sortable({ items: 'li:gt(0)', update: function (e, ui) { updateMenuSequence(); } }); $("#mnu").disableSelection();
           
    function updateMenuSequence() {
                var newIndex = ''; $("#mnu li:gt(0)").each(function () {
                    if (newIndex == '') { newIndex = "{'newMethQ':'" + $(this).attr('id'); }
                    else { newIndex += "," + $(this).attr('id'); }
                });
                newIndex += "'}"; $('.pros').show();
                $.ajax({ type: "POST", url: "PageName.aspx/UpdateSeq", data: newIndex,
                    contentType: "application/json; charset=utf-8", dataType: "json",
                    success: function (msg) { $('.pros').hide(); }, error: function (xhr, msg, e) { alert(msg.e); }
                });
            }
        });
    </script>

How to get Max & Min Number From Array List in C# Windows Application

-- Add this Name Space
using System.Collections;

ArrayList Numbers = new ArrayList();

-- Add Value in Array List
Random Randomizer = new Random();
Int32 P1 = Randomizer.Next(25, 100);
Int32 P2 = Randomizer.Next(25, 100);
Int32 P3 = Randomizer.Next(25, 100);
Int32 P4 = Randomizer.Next(25, 100);
Numbers.Add(P1);
Numbers.Add(P2);
Numbers.Add(P3);
Numbers.Add(P4);

-- Get Max Number
Int32 MaxNumber = Numbers.Cast<Int32>().Max();

-- Get Min Number
Int32 MaxNumber = Numbers.Cast<Int32>().Min();

Monday, June 10, 2013

How Find Column Name Use in Which Table Using SQL

select so.name
from sysobjects so inner join syscolumns sc
ON so.id = sc.id where sc.name = 'Name'

Result :

tblStudent
tblEtc

How to Conver Upper Case to First Letter Capital of Each Word in SQL

SELECT dbo.ProperCase('Hardik Deshani')

Result : Hardik Deshani

Create Function This Function:

CREATE FUNCTION [dbo].[ToTitleCase]
(@OriginalText VARCHAR(8000))
RETURNS VARCHAR(8000) 
BEGIN
DECLARE @CleanedText VARCHAR(8000)
;with
  a1 as (select 1 as N union all select 1 union all
         select 1      union all select 1 union all
         select 1      union all select 1 union all
         select 1      union all select 1 union all
         select 1      union all select 1),
  a2 as (select 1 as N from a1 as a cross join a1 as b),
  a3 as (select 1 as N from a2 as a cross join a2 as b),
  a4 as (select 1 as N from a3 as a cross join a2 as b),
  Tally as (select top (len(@OriginalText)) row_number() over (order by N) as N from a4)
 
SELECT @CleanedText = ISNULL(@CleanedText,'') + 
     --first char is always capitalized?
CASE WHEN Tally.N = 1 THEN UPPER(SUBSTRING(@OriginalText,Tally.N,1))
     WHEN SUBSTRING(@OriginalText,Tally.N -1,1) = ' '  THEN UPPER(SUBSTRING(@OriginalText,Tally.N,1))
     ELSE LOWER(SUBSTRING(@OriginalText,Tally.N,1))
END
    
FROM Tally WHERE Tally.N <= LEN(@OriginalText)           
               
RETURN @CleanedText
END

How to Select and add days or months or year in sql

SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate())+1, 0)
Result : 2013-06-11 00:00:00.000

SELECT DATEADD(dd, DATEDIFF(dd, 0, '2013-04-05')+5, 0)
Result : 2013-04-10 00:00:00.000

How To Select Days,Months, Years Between two dates

select DATEDIFF(dd,getdate(),'2013-04-15')
Result : -56

select DATEDIFF(mm,getdate(),'2013-04-15')
Result : -2

select DATEDIFF(yy,getdate(),'2013-04-15')
Result : 0

How to Add Days, Month, Year in Date Using Sql Server

select DATEADD(DAY, 1, getdate())
Result : 2013-06-11 16:22:33.920

select DATEADD(MONTH, 1, getdate())
Result : 2013-07-10 16:22:33.920

select DATEADD(YEAR, 1, getdate())
Result : 2014-06-10 16:22:33.920

Create Maths Quiz in C# Windows Application


Random randomizer = new Random();
int addend1;
int addend2;
int timeLeft;
int minuend;
int subtrahend;
int multiplicand;
int multiplier;
int dividend;
int divisor;

private void timer1_Tick(object sender, EventArgs e)
        {
            if (CheckTheAnswer())
            {
                timer1.Stop();
                MessageBox.Show("You got all the answers right!",
                                "Congratulations");
                startButton.Enabled = true;
            }
            else if (timeLeft > 0)
            {
                timeLeft--;
                timeLeftLabel.Text = timeLeft + " seconds";
            }
            else
            {
                timer1.Stop();
                timeLeftLabel.Text = "Time's up!";
                MessageBox.Show("You didn't finish in time.", "Sorry");
                sum.Value = addend1 + addend2;
                difference.Value = minuend - subtrahend;
                product.Value = multiplicand * multiplier;
                quotient.Value = dividend / divisor;
                startButton.Enabled = true;

            }
        }

public void StartTheQuiz()
        {
            // Fill in the addition problem.
            addend1 = randomizer.Next(51);
            addend2 = randomizer.Next(51);
            plusLeftLabel.Text = addend1.ToString();
            plusRightLabel.Text = addend2.ToString();
            sum.Value = 0;

            // Fill in the subtraction problem.
            minuend = randomizer.Next(1, 101);
            subtrahend = randomizer.Next(1, minuend);
            minusLeftLabel.Text = minuend.ToString();
            minusRightLabel.Text = subtrahend.ToString();
            difference.Value = 0;

            // Fill in the multiplication problem.
            multiplicand = randomizer.Next(2, 11);
            multiplier = randomizer.Next(2, 11);
            multLeftLabel.Text = multiplicand.ToString();
            multRightLabel.Text = multiplier.ToString();
            product.Value = 0;

            // Fill in the division problem.
            divisor = randomizer.Next(2, 11);
            int temporaryQuotient = randomizer.Next(2, 11);
            dividend = divisor * temporaryQuotient;
            divLeftLabel.Text = dividend.ToString();
            divRightLabel.Text = divisor.ToString();
            quotient.Value = 0;

            // Start the timer.
            timeLeft = 60;
            timeLeftLabel.Text = "60 seconds";
            timer1.Start();
        }

private bool CheckTheAnswer()
        {
            if ((addend1 + addend2 == sum.Value)
                && (minuend - subtrahend == difference.Value)
                && (multiplicand * multiplier == product.Value)
                && (dividend / divisor == quotient.Value))
                return true;
            else
                return false;
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            StartTheQuiz();
            startButton.Enabled = false;
        }

How to Display Reverse Number Or String in C# Windows Application


private void btReverse_Click(object sender, EventArgs e)
        {
            label1.Text = "";
            string inp = textBox1.Text;
            char[] outp = inp.ToCharArray();
            Array.Reverse(outp);
            foreach (var item in outp)
            {
                label1.Text += item.ToString();
            }
        }

Create Custmized Count Down Timer With Customized Message

-- Timer Start, Stop, Pause Facility in this timer Control


public int seconds; // Seconds.
public int minutes; // Minutes.
public int hours;   // Hours.
public bool paused; // State of the timer [PAUSED/WORKING].

private void btStart_Click(object sender, EventArgs e)
        {
            if (paused != true)
            {
                if ((textBox1.Text != "") && (textBox2.Text != "") && (textBox3.Text != ""))
                {
                    timer1.Enabled = true;
                    button1.Enabled = true;
                    button2.Enabled = false;
                    button3.Enabled = true;
                    textBox1.Enabled = false;
                    textBox2.Enabled = false;
                    textBox3.Enabled = false;
                    textBox4.Enabled = false;

                    try
                    {
                        minutes = System.Convert.ToInt32(textBox2.Text);
                        seconds = System.Convert.ToInt32(textBox3.Text);
                        hours = System.Convert.ToInt32(textBox1.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Incomplete settings!");
                }
            }
            else
            {
                timer1.Enabled = true;
                paused = false;
                button2.Enabled = false;
                button1.Enabled = true;
            }
        }

private void btPause_Click(object sender, EventArgs e)
        {
            // Pause the timer.
            timer1.Enabled = false;
            paused = true;
            button1.Enabled = false;
            button2.Enabled = true;
        }

private void btStop_Click(object sender, EventArgs e)
        {
            // Stop the timer.
            paused = false;
            timer1.Enabled = false;
            button1.Enabled = false;
            button3.Enabled = false;
            button2.Enabled = true;
            textBox4.Clear();
            textBox3.Clear();
            textBox2.Clear();
            textBox1.Clear();
            textBox1.Enabled = true;
            textBox4.Enabled = true;
            textBox3.Enabled = true;
            textBox2.Enabled = true;
            textBox1.Enabled = true;
            lblHr.Text = "00";
            lblMin.Text = "00";
            lblSec.Text = "00";
        }


private void timer1_Tick(object sender, EventArgs e)
        {
            // Verify if the time didn't pass.
            if ((minutes == 0) && (hours == 0) && (seconds == 0))
            {
                // If the time is over, clear all settings and fields.
                // Also, show the message, notifying that the time is over.
                timer1.Enabled = false;
                MessageBox.Show(textBox4.Text);
                button1.Enabled = false;
                button3.Enabled = false;
                button2.Enabled = true;
                textBox4.Clear();
                textBox3.Clear();
                textBox2.Clear();
                textBox1.Enabled = true;
                textBox4.Enabled = true;
                textBox3.Enabled = true;
                textBox2.Enabled = true;
                textBox1.Enabled = true;
                lblHr.Text = "00";
                lblMin.Text = "00";
                lblSec.Text = "00";
            }
            else
            {
                // Else continue counting.
                if (seconds < 1)
                {
                    seconds = 59;
                    if (minutes == 0)
                    {
                        minutes = 59;
                        if (hours != 0)
                            hours -= 1;

                    }
                    else
                    {
                        minutes -= 1;
                    }
                }
                else
                    seconds -= 1;
                // Display the current values of hours, minutes and seconds in
                // the corresponding fields.
                lblHr.Text = hours.ToString();
                lblMin.Text = minutes.ToString();
                lblSec.Text = seconds.ToString();
            }
        }

How to create Count Down Timer in C# Windows Application


public int hours = 00;   // Hours.
public int minutes = 10; // Minutes.
public int seconds = 00; // Seconds.

private void timer1_Tick(object sender, EventArgs e)
        {
            if (seconds < 1)
            {
                seconds = 59;
                if (minutes == 0)
                {
                    minutes = 59;
                    if (hours != 0) hours -= 1;
                }
                else
                {
                    minutes -= 1;
                }
            }
            else seconds -= 1;
            lblHr.Text = hours.ToString();
            lblMin.Text = minutes.ToString();
            lblSec.Text = seconds.ToString();
        }

private void CountDownTimer1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

Saturday, June 8, 2013

Close Windows Form Using Escape Key

Note : Keypreviw = True in Form Property

Then Write This Code in  KeyDown Event

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
            if (e.KeyCode == Keys.Escape)
                this.Close();
}

How to Select COM Port All Details Using C#

Add Two References

- using System.Management;
- using System.IO.Ports;

:: Write this code in page load event ::

ManagementObjectCollection ManObjReturn;
ManagementObjectSearcher ManObjSearch;
ManObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
ManObjReturn = ManObjSearch.Get();

foreach (ManagementObject ManObj in ManObjReturn)
{
                //int s = ManObj.Properties.Count;
                //foreach (PropertyData d in ManObj.Properties)
                //{
                //    MessageBox.Show(d.Name);
                //}
                MessageBox.Show(
                    "Device ID : " + ManObj["DeviceID"] + "\n"
                    + "PNP Device ID : " + ManObj["PNPDeviceID"] + "\n"
                    + "Name : " + ManObj["Name"] + "\n"
                    + "Caption : " + ManObj["Caption"] + "\n"
                    + "Description : " + ManObj["Description"] + "\n"
                    + "Provider Type : " + ManObj["ProviderType"] + "\n"
                + "Status : " + ManObj["Status"]);
}