Friday, December 7, 2012

Loop through selected row in a WPF datagrid

 if (dg.SelectedItems.Count > 0)
            {
                for (int i = 0; i < dg.SelectedItems.Count; i++)
                {
                    System.Data.DataRowView selectedRow = (System.Data.DataRowView)dg.SelectedItems[i];
                    MessageBox.Show( Convert.ToString(selectedRow.Row.ItemArray[2]));
                }
            }

Sunday, November 18, 2012

Send and Receive SMS using c# and GSM Library

//Send and Receive SMS using c# and GSM Library
//GSM Library is created by Stefan Mayr

//ProcessConnection.cs and COMPortInfo.cs are used to detect connected GSM Phone during //Window_Loaded_1 events of frmCommSettings.xaml.cs.



classDeclaration.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GSMComm
{
class classDeclaration
{
public static string Port{get;set;}
public static int BaudRate{get;set;}
public static int Timeout{get;set;}

}
}

ProcessConnection.cs

//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;
namespace GSMComm
{
public class ProcessConnection
{

public static ConnectionOptions ProcessConnectionOptions()
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.EnablePrivileges = true;
return options;
}

public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
{
ManagementScope connectScope = new ManagementScope();
connectScope.Path = new ManagementPath(@"\\" + machineName + path);
connectScope.Options = options;
connectScope.Connect();
return connectScope;
}
}
}

COMPortInfo.cs

//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;

namespace GSMComm
{
public class COMPortInfo
{

public string Name { get; set; }
public string Description { get; set; }
public COMPortInfo() { }
 public static List GetCOMPortsInfo()
{
List comPortInfoList = new List();
ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);

using (comPortSearcher)
{
string caption = null;

foreach (ManagementObject obj in comPortSearcher.Get())
{
if (obj != null)
{
object captionObj = obj["Caption"];
if (captionObj != null)
{
caption = captionObj.ToString();
if (caption.Contains("(COM"))
{
COMPortInfo comPortInfo = new COMPortInfo();
comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
comPortInfo.Description = caption;
comPortInfoList.Add(comPortInfo);
}
}
}
}
}
return comPortInfoList;
}

}
}

frmCommSettings.xaml.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Drawing;
using System.Collections;
using System.ComponentModel;

using GsmComm.GsmCommunication;

namespace GSMComm
{
///





/// Interaction logic for frmCommSettings.xaml
///

public partial class frmCommSettings : Window
{
public frmCommSettings()
{
InitializeComponent();

}

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
btnRefresh_Click(this, null);


cboBaudRate.Items.Add("9600");
cboBaudRate.Items.Add("19200");
cboBaudRate.Items.Add("38400");
cboBaudRate.Items.Add("57600");
cboBaudRate.Items.Add("115200");
cboBaudRate.Text="9600";

cboTimeout.Items.Add("150");
cboTimeout.Items.Add("300");
cboTimeout.Items.Add("600");
cboTimeout.Items.Add("900");
cboTimeout.Items.Add("1200");
cboTimeout.Items.Add("1500");
cboTimeout.Items.Add("1800");
cboTimeout.Items.Add("2000");
cboTimeout.Text="300";

}

private void btnTest_Click(object sender, RoutedEventArgs e)
{
//Auto Detect Connected Port

GsmCommMain comm = new GsmCommMain(cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", ""), Convert.ToInt32(cboBaudRate.Text), Convert.ToInt32(cboTimeout.Text));
//Manual Connection Test
//GsmCommMain comm = new GsmCommMain(cboPort.Text,Convert.ToInt32(cboBaudRate.Text),Convert.ToInt32(cboTimeout.Text));
try
{
comm.Open();
while (!comm.IsConnected())
{

if (MessageBox.Show(this, "No phone connected.", "Connection setup",MessageBoxButton.OK,MessageBoxImage.Error,MessageBoxResult.OK)==MessageBoxResult.OK)
{
comm.Close();
return;
}

}

comm.Close();
}
catch(Exception ex)
{
MessageBox.Show("Connection error: " + ex.Message, "Connection setup", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
MessageBox.Show("Successfully connected to the phone.", "Connection setup", MessageBoxButton.OK, MessageBoxImage.Information);
//For Manual Test
//classDeclaration.Port=cboPort.Text;

//For Auto Detect
classDeclaration.Port = cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", "");
classDeclaration.BaudRate=Convert.ToInt32(cboBaudRate.Text);
classDeclaration.Timeout = Convert.ToInt32(cboTimeout.Text);
btnOK.IsEnabled = true;
btnOK.IsDefault = true;
}

private void btnOK_Click(object sender, RoutedEventArgs e)
{
MainWindow f = new MainWindow();
f.Show();
this.Close();

}

private void btnExit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}

private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
cboPort.Items.Clear();
foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo())
{
cboPort.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
}
}
}


}

MainWindow.xaml.cs
//Add References to using GsmComm.PduConverter;using GsmComm.PduConverter.SmartMessaging;
//using GsmComm.GsmCommunication;using GsmComm.Interfaces;using GsmComm.Server;

//Goto Project->Add Reference->Browse->add the following files from C:\Program //Files\GSMComm\DotNet40 (Available only after GSMLibrary Installation)
// GSMCommServer.dll, GSMCommShared.dll, GSMCommunication.dll, PDUConverter.dll








using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using GsmComm.PduConverter;
using GsmComm.PduConverter.SmartMessaging;
using GsmComm.GsmCommunication;
using GsmComm.Interfaces;
using GsmComm.Server;

namespace GSMComm
{
///



/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
private GsmCommMain comm;
private bool registerMessageReceived;
public MainWindow()
{
InitializeComponent();

}

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
comm = null;
registerMessageReceived = false;
comm = new GsmCommMain(classDeclaration.Port, classDeclaration.BaudRate, classDeclaration.Timeout);
comm.Open();
pb.IsIndeterminate = false;
try
{
// Enable notifications about new received messages
if (!registerMessageReceived)
{
comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
registerMessageReceived = true;
}
comm.EnableMessageNotifications();
//MessageBox.Show("Message notifications activated.");

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void btnClear_Click(object sender, RoutedEventArgs e)
{

txtmessage.Text = "";

}


private void btnSend_Click(object sender, RoutedEventArgs e)
{

pb.IsIndeterminate = true;

// Thread.Sleep(60000);
try
{

// Send an SMS message
SmsSubmitPdu pdu;
// Send message in the default format
pdu = new SmsSubmitPdu(txtmessage.Text, txtno.Text);
pdu.RequestStatusReport = true;
comm.SendMessage(pdu);


MessageBox.Show(ShowMessage(pdu));

}
catch (CommException ex)
{

MessageBox.Show(ex.Message.ToString());
}
// }
pb.IsIndeterminate = false;
}


private void comm_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
IMessageIndicationObject obj = e.IndicationObject;
if (obj is ShortMessage)
{
ShortMessage msg = (ShortMessage)obj;
SmsPdu pdu = comm.DecodeReceivedMessage(msg);
MessageBox.Show("New message received.");
txtmessage.Text = ShowMessage(pdu);

}

if (obj is MemoryLocation)
{

MemoryLocation loc = (MemoryLocation)obj;
MessageBox.Show(string.Format("New message received in storage \"{0}\", index {1}.", loc.Storage, loc.Index));


}


}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}



}

private string GetMessageStorage()
{
string storage = string.Empty;
//if (rbMessageSIM.Checked)
storage = PhoneStorageType.Sim;
//if (rbMessagePhone.Checked)
// storage = PhoneStorageType.Phone;

if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}

private string ShowMessage(SmsPdu pdu)
{
string output;
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
output ="SENT/UNSENT MESSAGE" + "\n";
output = output + "Recipient: " + data.DestinationAddress + "\n";
output = output + "Message text: " + data.UserDataText + "\n";
return output;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
output = "RECEIVED MESSAGE" + "\n";
output = output + "Sender: " + data.OriginatingAddress + "\n";
output = output + "Sent: " + data.SCTimestamp.ToString() + "\n";
output = output + "Message text: " + data.UserDataText + "\n";

return output;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
output = "STATUS REPORT" + "\n";
output = output + "Recipient: " + data.RecipientAddress + "\n";
output = output + "Status: " + data.Status.ToString() + "\n";
output = output + "Timestamp: " + data.DischargeTime.ToString() + "\n";
output = output + "Message ref: " + data.MessageReference.ToString() + "\n";
return output;
}
MessageBox.Show("Unknown message type: " + pdu.GetType().ToString());
return null;
}

private void cmdPhoneInfo_Click(object sender, RoutedEventArgs e)
{
IdentificationInfo info = comm.IdentifyDevice();
txtmessage.Text = "";
txtmessage.Text = txtmessage.Text + "Manufacturer: " + info.Manufacturer + "\n";
txtmessage.Text = txtmessage.Text + "Model: " + info.Model + "\n";
txtmessage.Text = txtmessage.Text + "Revision: " + info.Revision + "\n";
txtmessage.Text = txtmessage.Text + "Serial number: " + info.SerialNumber + "\n";
}



private void cmdmsgstatus_Click(object sender, RoutedEventArgs e)
{
txtmessage.Text = "";
string storage = GetMessageStorage();
try
{
// Get memory status of the storage
MemoryStatus status = comm.GetMessageMemoryStatus(storage);
int percentUsed = (status.Total > 0) ? (int)((double)status.Used / (double)status.Total * 100) : 0;
txtmessage.Text = string.Format("Message memory status: {0} of {1} used ({2}% used, {3}% free)", status.Used, status.Total, percentUsed, 100 - percentUsed);

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void btnRead_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage

DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
foreach (DecodedShortMessage message in messages)
{

txtmessage.Text = string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);

}
MessageBox.Show(string.Format("{0,9} unread messages.", messages.Length.ToString()));

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}

private void btnReadAllMessages_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.All, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);

}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}

private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch (status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}

private void btnownnumber_Click(object sender, RoutedEventArgs e)
{


try
{
// Get the subscriber numbers
SubscriberInfo[] info2 = comm.GetSubscriberNumbers();
foreach (SubscriberInfo info in info2)
{
txtmessage.Text=string.Format("{0,-20}Type {1}, Speed {2}, Service {3}, ITC {4}, Alpha {5}",info.Number, info.Type, info.Speed, info.Service, info.Itc, info.Alpha) + "\n";
}
txtmessage.Text= string.Format("{0,9} number(s) found.", info2.Length.ToString());

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}

}

private void DeleteAllMessages()
{


string storage = GetMessageStorage();
try
{
// Delete all messages from phone memory
comm.DeleteMessages(DeleteScope.All, storage);
MessageBox.Show("All Messages Deleted from SIM");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}

}

private void btnoperator_Click(object sender, RoutedEventArgs e)
{
try
{
// List the operators detected by the phone
OperatorInfo2[] info2 = comm.ListOperators();
txtmessage.Text = "";
txtmessage.Text=txtmessage.Text + "Operator list:" + "\n";
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
foreach (OperatorInfo2 info in info2)
{
txtmessage.Text = txtmessage.Text + string.Format("Status: {0}\r\nComplete Name: {1}\r\nShorten Name: {2}\r\n Numeric: {3}\r\nAccess Technology: {4}", info.Status, info.LongAlphanumeric, info.ShortAlphanumeric, info.Numeric, info.AccessTechnology) + "\n";

}
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
txtmessage.Text = txtmessage.Text + string.Format("{0} operator(s) found.", info2.Length.ToString());

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}


}

private void Window_GotFocus_1(object sender, RoutedEventArgs e)
{

btnsignal_Click(sender,e);
}

private void btnsignal_Click(object sender, RoutedEventArgs e)
{

try
{
// Get signal quality
SignalQualityInfo info = comm.GetSignalQuality();

txtsignal.Text = "Signal Strength : " + info.SignalStrength.ToString() + "%";

}
catch (Exception)
{

txtsignal.Text="Signal Strength : 0%";
}

}



private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure you want to Exit?", "GSM Phone Project", MessageBoxButton.YesNo).Equals(MessageBoxResult.No))
{
e.Cancel = true;

}
else { comm.Close(); }

}

private void btnReadUnSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredUnsent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);

}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}

private void btnReadSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredSent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);

}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
}
}



Connect to MySQL Database using C#

//Retrieve data from MySQL database using native connection
//Install  MySQL Connector Net 6.3.7 or higher before using the code below
//Project->Add References->Browse->browse MySQL.Data.dll,MySQL.Data.Entity.dll,MySQL.Web.dll
//from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.3.7\Assemblies\v4.0

using MySql.Data;
using MySql.Data.MySqlClient;

MySqlDataAdapter da;
DataSet ds;

MySqlConnection conn = new MySqlConnection("server=localhost;user=UserName;database=DBName;port=3306;password=UserPassword");
conn.Open();
da = new MySqlDataAdapter(Replace_with_your_String_Selection, conn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);

ds = new DataSet();
da.Fill(ds, Replace_with_Table_Name);
conn.Close();

//MessageBox.Show(ds.Tables["tblName"].Rows[0].ItemArray[1].ToString());

//Insert, Update, Delete record from MySQL database
//Install  MySQL Connector Net 6.3.7 or higher before using the code below
//Project->Add References->Browse->browse MySQL.Data.dll,MySQL.Data.Entity.dll,MySQL.Web.dll //from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.3.7\Assemblies\v4.0

using MySql.Data;
using MySql.Data.MySqlClient;

MySqlConnection conn = new MySqlConnection("server=localhost;user=UserName;database=DBName;port=3306;password=UserPassword");
conn.Open();
MySqlCommand cmd = new MySqlCommand(Replace_with_your_INSERT_UPDATE_DELETE_Command, conn);
cmd.ExecuteNonQuery();
conn.Close();

// dg.ItemsSource = ds.Tables["tblName"].DefaultView;

Tuesday, October 9, 2012

Connect MySQL using C# (ODBC Connection)

Connect MySQL using C# (ODBC Connection)

//using System.Data.Odbc;
OdbcCommand ocmd;
OdbcDataAdapter da;

OdbcConnection dbcon = new OdbcConnection("DRIVER={MySQL ODBC 5.1 Driver};server=127.0.0.1;UID=admin;Password=admin;Persist Security Info=True;port=3308;Connection Reset=False;database=dbdata");

dbcon.Open();

da=new OdbcDataAdapter("SELECT * FROM `tblstudent` ORDER BY `Last_Name`,`First_Name`, `Middle_Name` ASC",dbcon);

ds = new DataSet();
da.Fill(ds,"tblstudent");
dbcon.Close();
MessageBox.Show(ds.Tables["tblstudent"].Rows[5].ItemArray[3].ToString());




// INSERT, UPDATE, DELETE
 OdbcCommand ocmd;
OdbcDataAdapter da;  
OdbcConnection dbcon = new OdbcConnection("DRIVER={MySQL ODBC 5.1 Driver};server=127.0.0.1;UID=admin;Password=admin;Persist Security Info=True;port=3308;Connection Reset=False;database=dbdata");   
dbcon.Open();         
           
ocmd=new OdbcCommand("INSERT INTO tblstudent (`Stud_ID`) VALUES('00-99999')",dbcon);
ocmd.ExecuteNonQuery();
dbcon.Close();

Sunday, October 7, 2012

Connect MS Access using C# (OleDB Connection)

Connect MS Access using C#  (OleDB Connection)

//Add References
//using System.Data.OleDb;
//Retrieving Record

            DataSet ds;
            OleDbCommand ocmd;
            OleDbDataAdapter da;
            OleDbConnection dbcon = new OleDbConnection("PROVIDER=microsoft.jet.oledb.4.0;data source =" + System.AppDomain.CurrentDomain.BaseDirectory + "\\dbase\\dbase.mdb");
            dbcon.Open();
            da = new OleDbDataAdapter("SELECT * FROM `tblstudent` ORDER BY `Last_Name`,`First_Name`, `Middle_Name` ASC", dbcon);
            ds = new DataSet();
            da.Fill(ds, "tblstudent");
            dbcon.Close();
            MessageBox.Show(ds.Tables["tblstudent"].Rows[5].ItemArray[3].ToString());

//INSERT, UPDATE, DELETE Record

OleDbCommand ocmd;

OleDbDataAdapter da;

 OleDbConnection dbcon = new OleDbConnection("PROVIDER=microsoft.jet.oledb.4.0;data source =" + System.AppDomain.CurrentDomain.BaseDirectory + "\\dbase\\dbase.mdb");

    dbcon.Open();

ocmd=new OleDbCommand("INSERT INTO tblstudent (`Stud_ID`) VALUES('00-99999')",dbcon);          

ocmd.ExecuteNonQuery();       

 dbcon.Close();

Saturday, October 6, 2012

How to add ResourceDictionary.xaml to your existing c# WPF Application

//How to add ResourceDictionary.xaml to your existing c# WPF Application
 //Goto ->Project, Add New Existing Project, then browse your ResourceDictionary
//-> copy the highlighted text inside app.xaml between Application.Resources
//please note that my ResourceDictionary1.xaml is inside a folder name Resources
//remove ResourceDictionary2.xaml if it is not available and rename ResourceDictionary1.xaml according
//to your Resource Dictionary file.

   
       
       
           
               
               
           

       

   

Friday, October 5, 2012

How do i escape single qoute (') in MySQL using c#

How do i escape single qoute (') in MySQL using c#

if you want to insert a data with a single qoue (') like the example below:

INSERT INTO tblname (`Field1`) VALUES ('5'4');

then you need to escape the single qoute (') using backslash (\), the correct SQL would be,


INSERT INTO tblname (`Field1`) VALUES ('5\'4');

to do that in c# assuming 5'4 is inside a textbox name txtheight, then the code will look like this,

 INSERT INTO tblname (`Field1`) VALUES ('" + txtheight.Text.Replace("'","\'") + "');

or

String.Format("INSERT INTO tbl (`Name`) VALUES ('{0}')", txtheight.Text.Replace("'","\'"))

Wednesday, October 3, 2012

Retrieve Local IP using c#

Retrieve Local IP using c#, Get Local IP using c#

//add System.Net namespace
//using System.Net;
  
            string localIP = "";
            foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            MessageBox.Show(localIP);

Monday, October 1, 2012

Read and Write Text File Line by Line using c#


//Read and Write Text File Line by Line using c#
//TextBlock  property:
//AcceptsReturn :checked
//AcceptsTab: checked

//Add Reference

using Microsoft.Win32;

private void btnbrowse_Click(object sender, RoutedEventArgs e)
        {
            String AppPath = System.AppDomain.CurrentDomain.BaseDirectory;
            OpenFileDialog dlg = new OpenFileDialog() { DefaultExt = ".jpg" };
          

            dlg.Filter = "txt (.txt)|*.txt";
            dlg.ShowDialog();

            try
            {
                //if (System.IO.Directory.Exists(AppPath + "images") == false)
                //{
                //    System.IO.Directory.CreateDirectory(AppPath + "images");
                //}

                txtfile.Text = dlg.FileName.ToString();
                             

                //throw new Exception("");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            //btnNew.Visibility = Visibility.Hidden;
        }

        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            int counter = 0;
            string line;
            txt.Text = "";
            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(txtfile.Text);
            while ((line = file.ReadLine()) != null)
            {
                txt.Text = txt.Text + line +"\n";
                counter++;
            }

            file.Close();

        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txt.Text = "";
        }

        private void btnWrite_Click(object sender, RoutedEventArgs e)
        {
          
            // Read the file and display it line by line.
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(txtfile.Text);

                file.WriteLine(txt.Text);
                file.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
          
        }

Tuesday, August 28, 2012

c# (c Sharp) wpf 2010 using Excel

c# (c Sharp) wpf 2010 using Excel, wpf 2010 using Excel
Code to access Excel File using c# wpf 2010


//Add reference to Microsoft.Office.Interop.Excel
//Goto Project->Add Reference->.NET and look for Microsoft.Office.Interop.Excel, then click OK

//Type reference to Excel

using Excel = Microsoft.Office.Interop.Excel;


//Type the code below on your trigger button
Excel.Application ExcelApp = new Excel.Application();

//To create a new Workbook
//Excel.Workbook WBook = ExcelApp.Workbooks.Add();

//To open existing workbook
//Here I'm opening an Excel File named Workbook.xlsx found on my bin/debug folder, inside "Excel Files" folder.

Excel.Workbook WBook = ExcelApp.Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory + "Excel Files\\Workbook.xlsx", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);


//To create a Sheets object that holds the Worksheets within the workbook
Excel.Sheets AllSheets = WBook.Worksheets;

//To read individual worksheet
Excel.Worksheet WSheets = (Excel.Worksheet)AllSheets.get_Item("Test_Sheet");
WSheets.Select();

//To display Excel Application while working
ExcelApp.Visible = true;

//Set the value of cell A1 to "www.kreativeidea21.blogspot.com"
WSheets.get_Range("A1", "A1").Value = "www.kreativeidea21.blogspot.com";


//Shows how to retrieve data from cell a1.
//A redline will appear under Message.Show, this is NOT an error.
MessageBox.Show(WSheets.get_Range("A1", "A1").Value);


MessageBox.Show("press any key to exit!");


//To save updated sheet
WBook.Save();

//To close sheet
WBook.Close();

//To free up memmory and close excel
ExcelApp.Quit();

Friday, July 20, 2012

c# wpf Numbers Format and Date Format

c# wpf Numbers Format and Date Format

This entry has been copied from SteveX (http://blog.stevex.net/index.php/string-formatting-in-csharp/) for my own easy reference.

The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Strings

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.
Sample Generates
String.Format(”->{1,10}<-”, “Hello”); -> Hello<-
String.Format(”->{1,-10}<-”, “Hello”); ->Hello <-

Numbers

Basic number formatting specifiers:

Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90

Custom number formatting:

Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.

;
Group separator
see below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.

Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002

The ‘U’ specifier seems broken; that string certainly isn’t sortable.

Custom date formatting:

Specifier Type Example Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, … Second fractions {0:fff} 932
gg, … Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002

Enumerations

Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.

Some Useful Examples

String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);

This will output “$1,240.00? if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

String.Format(”{0:(###) ###-####}”, 8005551212);

This will output “(800) 555-1212?.