Tuesday, September 20, 2011

Intercommunication Process Using TCP

//Here is the method to send some strings through a port

// Create a new instance of TCPListener and indicate the port
TcpListener l = new TcpListener(1001);
// Start Listener
l.Start();
// wait for client to make request
TcpClient c = l.AcceptTcpClient(); 
// access steam to send data to client.
NetworkStream ns = c.GetStream(); 

// get system date and convert it to string
string st = txtSend.Text; 

//convert string to an array of Bytes
byte[] buf = System.Text.Encoding.ASCII.GetBytes(st); 
//write to stream
ns.Write(buf, 0, st.Length);

// Stop Listener
l.Stop();

//Here is the method to Receive some strings through a port

// Create a new instance of TCPClient and indicate the port
TcpClient c = new TcpClient("localhost", 1001);

// get stream
NetworkStream ns = c.GetStream(); 

// create byte array to receive data
byte[] buf = new byte[100];  

//read data from stream into byte array
ns.Read(buf, 0, 100);
// convert byte array to string
string st = System.Text.Encoding.ASCII.GetString(buf);


        

Wednesday, June 29, 2011

Generate a Excel file with multiple sheets (Visual Basic)

Dim xlApp As Excel.Application = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkSheet As Excel.Worksheet
Dim xlWorkSheets As Excel.Worksheets = Nothing
Dim xlRange As Excel.Range = Nothing
Dim FileSend As String
Dim str As New Bitacora.Subject
Dim Msg As String

Try
'Creating a new object of the excel application object
xlApp = New Excel.Application
'Hiding the excel application
xlApp.Visible = False
'Hiding all the alert messages occurring during the process
xlApp.DisplayAlerts = False

'Adding a collection of workbooks to the excel object
xlWorkBook = CType(xlApp.Workbooks.Add(), Excel.Workbook)
'Saving the workbook as a normal workbook format
xlWorkBook.SaveAs(FileName, Excel.XlFileFormat.xlWorkbookNormal)

'Gettin the path
FileSend = xlWorkBook.Path & "\" & FileName
'Getting the collection of workbooks in an object
xlWorkBooks = xlApp.Workbooks
'Get the reference to the first sheet in the workbook collection in a variable
xlWorkSheet = CType(xlWorkBooks(1).Worksheets.Item(1), Excel.Worksheet)

'The name of the worksheet
xlWorkSheet.Name = "Pendientes"

'Get the cells collection of the sheet in a variable to write the data
xlRange = xlWorkSheet.Cells
'Calling the function to write the datatable data in the cells of the first sheet
dt = fun.PendientesGenerados(datos.nAgente, datos.nAgenteBck, Fecha)
str.PGenerados = dt.Rows.Count
WriteData(dt, xlRange)

'Setting the width of the specified range of cells so as to absolutely fit the written data
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'2nd Sheet
xlWorkSheet = xlWorkBook.Worksheets.Add
xlWorkSheet.Name = "TicketsActualizados"
xlRange = xlWorkSheet.Cells
dt = fun.TicketsActualizados(datos.nAgente, datos.nAgenteBck, Fecha)
str.TModificados = dt.Rows.Count
WriteData(dt, xlRange)
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'3rd Sheet
xlWorkSheet = xlWorkBook.Worksheets.Add
xlWorkSheet.Name = "TicketsRecibidos"
xlRange = xlWorkSheet.Cells
dt = fun.TicketsRecibidos(datos.nAgente, datos.nAgenteBck, Fecha)
str.TRecibidos = dt.Rows.Count
WriteData(dt, xlRange)
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'4th Sheet
xlWorkSheet = xlWorkBook.Worksheets.Add
xlWorkSheet.Name = "TicketsGenerados"
xlRange = xlWorkSheet.Cells
dt = fun.TicketsGenerados(datos.nAgente, datos.nAgenteBck, Fecha)
str.TGenerados = dt.Rows.Count
WriteData(dt, xlRange)
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'5th Sheet
xlWorkSheet = xlWorkBook.Worksheets.Add
xlWorkSheet.Name = "TransaccionesIngresadas"
xlRange = xlWorkSheet.Cells
dt = fun.TransaccionesIngresadas(datos.nAgente, datos.nAgenteBck, Fecha)
str.TIngresadas = dt.Rows.Count
WriteData(dt, xlRange)
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'6th Sheet
xlWorkSheet = xlWorkBook.Worksheets.Add
xlWorkSheet.Name = "ClientesContactados"
xlRange = xlWorkSheet.Cells
dt = fun.ClientesContactados(datos.nAgente, datos.nAgenteBck, Fecha)
str.CContactados = dt.Rows.Count
WriteData(dt, xlRange)
xlWorkSheet.Range("A1", "Z1").EntireColumn.AutoFit()

'Delete Sheets
For Each sheet As Excel.Worksheet In xlWorkBook.Sheets
If sheet.Name = "Sheet2" Or sheet.Name = "Sheet3" Then
sheet.Delete()
End If

Next
xlWorkSheet.SaveAs(FileName)
xlWorkBook.Close()
xlWorkBook = Nothing

Show a ToolTip on a Control

ToolTip buttonToolTip = new ToolTip();
//Title of tooltip window
buttonToolTip.ToolTipTitle = "Ivan Osorio De anda";
//Represents weather a fade effect should be used when displaying the tooltip
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
//Gets or sets a value indicating whether the ToolTip should use a balloon window
buttonToolTip.IsBalloon = true;
buttonToolTip.ToolTipIcon = ToolTipIcon.Info;
//Displays if tooltip is displayed even the parent control is not active.
buttonToolTip.ShowAlways = true;
               
//The period of time the ToolTip remains visible if the pointer is stationary on a control with specified ToolTip text.
buttonToolTip.AutoPopDelay = 5000;
//Gets or sets the time that passes before the ToolTip appears.
buttonToolTip.InitialDelay = 20;
//Gets or sets the length of time that must transpire before subsequent ToolTip windows appear as the pointer moves from one control to another.
buttonToolTip.ReshowDelay = 25;
//call SetToolTip method and pass a control and text
buttonToolTip.SetToolTip(DataGridViewTest, "Message!!");

Tuesday, April 12, 2011

How To Become a Better Programmer

Interesting Post.
http://www.codinghorror.com/blog/2007/01/how-to-become-a-better-programmer-by-not-programming.html

Does accumulating experience through the years necessarily make programming easier?


Bill Gates: No. I think after the first three or four years, it's pretty cast in concrete whether you're a good programmer or not. After a few more years, you may know more about managing large projects and personalities, but after three or four years, it's clear what you're going to be. There's no one at Microsoft who was just kind of mediocre for a couple of years, and then just out of the blue started optimizing everything in sight. I can talk to somebody about a program that he's written and know right away whether he's really a good programmer.

Friday, March 11, 2011

Interprocess Communication using Named Pipes in C#

Named pipes are a great way to communicate between multiple processes. What's makes them even better is that the processes don't have to share the same language.

A named pipe is a named, one-way or duplex pipe for communication between the pipe server and one or more pipe clients.

Any process can act as both a server and a client, making peer-to-peer communication possible. As used here, the term pipe server refers to a process that creates a named pipe, and the term pipe client refers to a process that connects to an instance of a named pipe. The server-side function for instantiating a named pipe is CreateNamedPipe. The server-side function for accepting a connection is ConnectNamedPipe. A client process connects to a named pipe by using the CreateFile or CallNamedPipe function.


Server Side:
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out))
{
     pipeServer.WaitForConnection();
     try
     {
          using (StreamWriter sw = new StreamWriter(pipeServer))
          {
           sw.AutoFlush = true;
           sw.WriteLine("Mensaje");
           }
     }
     catch (IOException ex)
     {
          MessageBox.Show("ERROR: {0}", ex.Message);
     }
}

Client Side:  
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In))
{
     try
      {
           pipeClient.Connect(2000);
           using (StreamReader sr = new StreamReader(pipeClient))
           {
                string temp = string.Empty;
                while ((temp = sr.ReadLine()) != null)
           {
           label4.Text = "Received from server: ";
           textBox1.Text = temp;
     }
     catch (Exception ex) { }

Tuesday, March 8, 2011

Show Context Menu on DataGridView

private void gridCoutas_MouseUp(object sender, MouseEventArgs e)
{
          DataGridView.HitTestInfo hitTestInfo;
         if (e.Button == MouseButtons.Right)
          {
            hitTestInfo = gridCoutas.HitTest(e.X, e.Y);

           if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex >= 0)
           {
                ContextMenu RighMenu = new ContextMenu();
                MenuItem Delete = new MenuItem();
                Delete.Text = "Eliminar";
                Delete.Click += (s, ea) =>
                {
                MessageBox.Show(Row.Couta.ToString());
                 };
                RighMenu.MenuItems.Add(Delete);
               RighMenu.Show(gridCoutas, new Point(e.X, e.Y));
          }
    }
}

Friday, February 18, 2011

Show Context Menu in the Grid Control

private void gridViewPendientes_ShowGridMenu(object sender, GridMenuEventArgs e)
{
         // Check whether a row is right-clicked.
         if (e.MenuType == GridMenuType.Row)
          {
                //Clear Items from a Menu
                e.Menu.Items.Clear();

               //Create a new MenuItem
               DXMenuItem Nuevo = new DXMenuItem();
               Nuevo.Caption = "Nuevo Proyecto";

               //Activa the EventHandler
               Nuevo.Click += new EventHandler(Nuevo_Click);

               //Add to the menu
               e.Menu.Items.Add(Nuevo);

               DXMenuItem Agregar = new DXMenuItem();
               Agregar.Caption = "Agregar a Proyecto";
               Agregar.Click += new EventHandler(Agregar_Click);
               e.Menu.Items.Add(Agregar);
       }
}

Sunday, February 13, 2011

 
 
 
 
 
 
AliasCLR type
stringSystem.String
sbyteSystem.SByte
byteSystem.Byte
shortSystem.Int16
ushortSystem.UInt16
intSystem.Int32
uintSystem.UInt32
longSystem.Int64
ulongSystem.UInt64
charSystem.Char
floatSystem.Single
doubleSystem.Double
boolSystem.Boolean
decimalSystem.Decimal

Thursday, January 6, 2011

Import Excel using OLEDB

You may need to impor a namespace:
using System.Data.OleDb;

//New DataTAble
table = new DataTable();

//Conection Straig For Excel Files
//FilePath is the direccion where the file is stored
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + FilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";

//Establish Coneccion
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.Connection = conn;

//Query for the Sheet
//Hoja is the name of the sheet
comm.CommandText = "SELECT * FROM ["+ Hoja +"$]";

//Execute Query and stores in a DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = comm;
adapter.Fill(table);
conn.Close();

//Then you can put the informacion in a grid
//MyGrid.DataSource = table
//Or take the table and insert into a databases

Export to Excel using StreamWriter Interop

You need to impor:
using excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
 
//Variables
excel.Application App;
excel.Workbook WB;
excel.Worksheet wsheet;
excel.Range range;

//Open New Instance of Excel
App = new excel.Application();
App.Visible = true;
App.DisplayAlerts = false;

//New Workbook
WB = App.Workbooks.Add(Missing.Value);

//New Sheet
wsheet = (excel.Worksheet)WB.ActiveSheet;
wsheet.Name = "Hoja";

//Procces DataTable
int Aux = 1;
foreach (DataRow row in table.Rows)
{
     Aux+=1;
     for (int i = 1; i < table.Columns.Count + 1; i++)
     {
          //Add Headers
          if (Aux == 2)
          {
               wsheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
          }
          wsheet.Cells[Aux, i] = row[i - 1].ToString();
     }
}

Export to Excel using StreamWriter

I assume that you had filled a datagriview with a datatable and add namespace System.IO

// Set location to save the file, name and extension
SaveFileDialog SaveFile = new SaveFileDialog();
SaveFile.DefaultExt = "csv";
SaveFile.FileName = "HojaTest";
SaveFile.Filter = "csv";
 
if (SaveFile.ShowDialog() == DialogResult.OK)
{
SaveFile.AddExtension = true;
//Create File
StreamWriter sw = new StreamWriter(SaveFile.FileName, false);
string Headers = "";
 
//Write headers to the file
foreach (DataGridViewColumn col in grid.Columns)
{
    if (Headers != "")
         Headers += ",";
    Headers += col.Name;
}
sw.Write(Headers);
sw.Write(sw.NewLine); 
 
//Write the informacion to excel file
foreach (DataRow row in table.Rows)
{
     for (int i = 0; i < table.Columns.Count ; i++)
     {
           if (!row[i].Equals(DBNull.Value))
                sw.Write(row[i].ToString().Replace(",", "."));
           if (i < table.Columns.Count - 1)
                 sw.Write(",");
      }
sw.Write(sw.NewLine);
}
sw.Close();
MessageBox.Show("Datos Exportados");