Tag Archive for c

C API for a python extension module

==> sonmodule.h <==
typedef struct {
PyObject_HEAD
PyObject *str;
int num;
} Son;

#define MAKE_SON_NEW(self, type, rt_error)
(self) = (Son *)(type)->tp_alloc((type), 0);
if ((self) == rt_error) { return rt_error; }

(self)->str = PyString_FromString("");
if ((self)->str == rt_error) {
Py_DECREF((self));
return rt_error;
}

(self)->num = 0

#ifdef __SON_MODULE
/* ---------- inclue form sonmodule.c ---------- */
static PyTypeObject SonType;

#else
/* ---------- inclue form othere module to use api ---------- */
/* store all api here */
void **Son_API;
/* set alias for easy call */
#define SonType (*(PyTypeObject *)Son_API[0])
#define Son_info (*(PyObject *(*) (Son *))Son_API[1])

static int _import_son(void)
{
PyObject *son = PyImport_ImportModule("son");
PyObject *c_api = NULL;
if (son == NULL){ return -1; }

/* load c api */
c_api = PyObject_GetAttrString(son, "_Son_API");
if (c_api == NULL) {Py_DECREF(son); return -1;}
if (PyCObject_Check(c_api)) {
Son_API = (void **)PyCObject_AsVoidPtr(c_api);
}
Py_DECREF(c_api);
Py_DECREF(son);
if (Son_API == NULL) return -1;

return 0;
}

#define import_son()
{
if (_import_son() < 0) {
PyErr_Print();
PyErr_SetString( PyExc_ImportError,
"son failed to import");
return;
}
}

#endif
/* __SONMODULE */

==> sonmodule.c <==
#include <Python.h>
#include "structmember.h"

#define __SON_MODULE
#include "sonmodule.h"
#undef __SON_MODULE

static void
Son_dealloc(Son* self)
{
Py_XDECREF(self->str);
self->ob_type->tp_free((PyObject*)self);
}

static PyObject *
Son_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Son *self;
MAKE_SON_NEW(self, type, NULL);
return (PyObject *)self;
}

static int
Son_init(Son *self, PyObject *args, PyObject *kwds)
{
PyObject *str=NULL, *tmp;

static char *kwlist[] = {"str", "num", NULL};

if (! PyArg_ParseTupleAndKeywords(args, kwds, "|Si", kwlist,
&str,
&self->num)){
return -1;
}

if (str) {
tmp = self->str;
Py_INCREF(str);
self->str = str;
Py_DECREF(tmp);
}

return 0;
}

static PyMemberDef Son_members[] = {
{"num", T_INT, offsetof(Son, num), 0, "Sone num"},
{NULL}  /* Sentinel */
};

static PyObject *
Son_getstr(Son *self, void *closure)
{
Py_INCREF(self->str);
return self->str;
}

static int
Son_setstr(Son *self, PyObject *value, void *closure)
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the str attribute");
return -1;
}

if (! PyString_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"The str attribute value must be a string");
return -1;
}

Py_DECREF(self->str);
Py_INCREF(value);
self->str = value;

return 0;
}

static PyGetSetDef Son_getseters[] = {
{"str", (getter)Son_getstr, (setter)Son_setstr, "str", NULL},
{NULL}  /* Sentinel */
};

static PyObject *
Son_info(Son *self)
{
PyObject *dic = PyDict_New();
if (dic == NULL) {
printf("creating dict failed
");
return NULL;
}
Py_INCREF(self->str);
PyDict_SetItemString(dic, "str", self->str);
PyDict_SetItemString(dic, "num", PyLong_FromLong( self->num ));
return dic;
}

static PyMethodDef Son_methods[] = {
{"info", (PyCFunction)Son_info, METH_NOARGS, "return info dic"},
{NULL}  /* Sentinel */
};

static PyTypeObject SonType = {
PyObject_HEAD_INIT(NULL)
0,				/*ob_size*/
"son.Son",			/*tp_name*/
sizeof(Son),			/*tp_basicsize*/
0,				/*tp_itemsize*/
(destructor)Son_dealloc,	/*tp_dealloc*/
0,				/*tp_print*/
0,				/*tp_getattr*/
0,				/*tp_setattr*/
0,				/*tp_compare*/
0,				/*tp_repr*/
0,				/*tp_as_number*/
0,				/*tp_as_sequence*/
0,				/*tp_as_mapping*/
0,				/*tp_hash */
0,				/*tp_call*/
0,				/*tp_str*/
0,				/*tp_getattro*/
0,				/*tp_setattro*/
0,				/*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags*/
"Son objects",		/* tp_doc */
0,				/* tp_traverse */
0,				/* tp_clear */
0,				/* tp_richcompare */
0,				/* tp_weaklistoffset */
0,				/* tp_iter */
0,				/* tp_iternext */
Son_methods,			/* tp_methods */
Son_members,			/* tp_members */
Son_getseters,		/* tp_getset */
0,				/* tp_base */
0,				/* tp_dict */
0,				/* tp_descr_get */
0,				/* tp_descr_set */
0,				/* tp_dictoffset */
(initproc)Son_init,		/* tp_init */
0,				/* tp_alloc */
Son_new,			/* tp_new */
};

static PyMethodDef module_methods[] = {
{NULL}  /* Sentinel */
};

/* ---------- insert object into api array ---------- */
void *Son_API[] = {
(void *) &SonType,
(void *) Son_info,
};

#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initson(void)
{
PyObject *m, *d;
PyObject *c_api;
if (PyType_Ready(&SonType) < 0){ return; }

m = Py_InitModule3("son", module_methods,
"Son Class");

if (m == NULL){ goto err; }

Py_INCREF(&SonType);
PyModule_AddObject(m, "Son", (PyObject *)&SonType);

/* ----- set api to module ----- */
d = PyModule_GetDict(m);
if (!d){ goto err; }

c_api = PyCObject_FromVoidPtr((void *)Son_API, NULL);
if (c_api == NULL){ goto err; }
PyDict_SetItemString(d, "_Son_API", c_api);
Py_DECREF(c_api);

return;

err:
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError,
"cannot load son module.");
}
return;
}

==> fathermodule.c <==
#include <Python.h>
#include "structmember.h"

#include "sonmodule.h"

typedef struct {
PyObject_HEAD
Son *son;
} Father;

static void
Father_dealloc(Father* self)
{
Py_XDECREF(self->son);
self->ob_type->tp_free((PyObject*)self);
}

static PyObject *
Father_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Father *self;

self = (Father *)type->tp_alloc(type, 0);
if (self == NULL) { return NULL; }

MAKE_SON_NEW(self->son, &SonType, NULL);

return (PyObject *)self;
}

static int
Father_init(Father *self, PyObject *args, PyObject *kwds)
{
return 0;
}

static PyMemberDef Father_members[] = {
{NULL}  /* Sentinel */
};

static PyObject *
Father_getson(Father *self, void *closure)
{
Py_INCREF(self->son);
return (PyObject *)self->son;
}

static int
Father_setson(Father *self, PyObject *value, void *closure)
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the son attribute");
return -1;
}

if (! PyObject_TypeCheck(value, &SonType)) {/* SonType is from Son_API! */
PyErr_SetString(PyExc_TypeError,
"The str attribute value must be a Son");
return -1;
}

Py_DECREF(self->son);
Py_INCREF(value);
self->son = (Son *)value;

return 0;
}

static PyGetSetDef Father_getseters[] = {
{"son", (getter)Father_getson, (setter)Father_setson, "son", NULL},
{NULL}  /* Sentinel */
};

static PyObject *
Father_info(Father *self)
{
PyObject *dic = PyDict_New();
if (dic == NULL) {
printf("creating dict failed
");
return NULL;
}
PyDict_SetItemString(dic, "son",
Son_info(self->son));/* Son_info is from Son_API! */
return dic;
}

static PyMethodDef Father_methods[] = {
{"info", (PyCFunction)Father_info, METH_NOARGS, "return info dic"},
{NULL}  /* Sentinel */
};

static PyTypeObject FatherType = {
PyObject_HEAD_INIT(NULL)
0,                         /*ob_size*/
"father.Father",             /*tp_name*/
sizeof(Father),             /*tp_basicsize*/
0,                         /*tp_itemsize*/
(destructor)Father_dealloc, /*tp_dealloc*/
0,                         /*tp_print*/
0,                         /*tp_getattr*/
0,                         /*tp_setattr*/
0,                         /*tp_compare*/
0,                         /*tp_repr*/
0,                         /*tp_as_number*/
0,                         /*tp_as_sequence*/
0,                         /*tp_as_mapping*/
0,                         /*tp_hash */
0,                         /*tp_call*/
0,                         /*tp_str*/
0,                         /*tp_getattro*/
0,                         /*tp_setattro*/
0,                         /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Father objects",           /* tp_doc */
0,		               /* tp_traverse */
0,		               /* tp_clear */
0,		               /* tp_richcompare */
0,		               /* tp_weaklistoffset */
0,		               /* tp_iter */
0,		               /* tp_iternext */
Father_methods,             /* tp_methods */
Father_members,             /* tp_members */
Father_getseters,           /* tp_getset */
0,                         /* tp_base */
0,                         /* tp_dict */
0,                         /* tp_descr_get */
0,                         /* tp_descr_set */
0,                         /* tp_dictoffset */
(initproc)Father_init,      /* tp_init */
0,                         /* tp_alloc */
Father_new,                 /* tp_new */
};

static PyMethodDef module_methods[] = {
{NULL}  /* Sentinel */
};

#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initfather(void)
{
PyObject* m;
if (PyType_Ready(&FatherType) < 0){ return; }

m = Py_InitModule3("father", module_methods,
"Father Class");

if (m == NULL){ return; }

Py_INCREF(&FatherType);
PyModule_AddObject(m, "Father", (PyObject *)&FatherType);

import_son();
}

==> setup.py <==
# python setup.py build build_ext --inplace
import sys
import os
from distutils.core import setup, Extension

son_module = Extension(
'son',
define_macros = [],
include_dirs = [],
libraries = [],
library_dirs = [],
extra_compile_args = [],
sources = ['sonmodule.c'])

father_module = Extension(
'father',
define_macros = [],
include_dirs = [],
libraries = [],
library_dirs = [],
extra_compile_args = [],
sources = ['fathermodule.c'])

setup(
name = 'storage',
version = '1.0',
description = '',
ext_modules = [son_module, father_module] )

==> test.txt <==
>>> import son
>>> sn = son.Son()
>>> import father
>>> fr = father.Father()
>>> sn.num = 12
>>> sn.str = "son str"
>>> sn.info()
{'num': 12L, 'str': 'son str'}
>>> fr.son
<son.Son object at 0xb7cd5070>
>>> fr.son.info()
{'num': 0L, 'str': ''}
>>> fr.info()
{'son': {'num': 0L, 'str': ''}}
>>> fr.son = sn
>>> fr.info()
{'son': {'num': 12L, 'str': 'son str'}}

source

Using GNULib’s GString in C

GString *myString = g_string_new("Starting string value");
// To print the string, often it is necessary to point to the gchar * str value:
print(myString->str);

source

Fuse basic example compilation

sudo apt-get install fuse-source fuse-utils libfuse-dev libfuse2

gcc -lfuse -D_FILE_OFFSET_BITS=64 hello.c -o hello

source

Screen Scraping, ViewState, and Authentication using ASP.Net

byte[] response;

WebClient webClient = new WebClient();
response = webClient.DownloadData(LOGIN_URL);

string viewstate = ExtractViewState(
Encoding.ASCII.GetString(response)
);

string postData = String.Format(
"__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login",
viewstate, USERNAME, PASSWORD);

webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
response = webClient.UploadData(
LOGIN_URL, "POST", Encoding.ASCII.GetBytes(postData)
);

private string ExtractViewState(string s)
{
string viewStateNameDelimiter = "__VIEWSTATE";
string valueDelimiter = "value="";

int viewStateNamePosition = s.IndexOf(viewStateNameDelimiter);
int viewStateValuePosition = s.IndexOf(
valueDelimiter, viewStateNamePosition
);

int viewStateStartPosition = viewStateValuePosition +
valueDelimiter.Length;
int viewStateEndPosition = s.IndexOf(""", viewStateStartPosition);

return HttpUtility.UrlEncodeUnicode(
s.Substring(
viewStateStartPosition,
viewStateEndPosition - viewStateStartPosition
)
);
}

source

GridView stuff

<asp:GridView
id="gvGridView"
runat="server"
AutoGenerateColumns="False"
>
<Columns>

</Columns>
</asp:GridView>

gvGridView.DataSource = dtDataTable;
gvGridView.DataBind();

<asp:TemplateField>
<ItemTemplate>
<a href='default.aspx?cid=<%# Eval("id") %>&sid=<%=Request.QueryString["id"].ToString()%>'><%# Eval("Column") %></a>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="" HeaderText="" HtmlEncode="false" DataFormatString="{0:MM/dd/yyyy}" SortExpression="" />

<asp:HyperLinkField
DataNavigateUrlFields="ID"
DataTextFormatString="{0}"
DataNavigateUrlFormatString="default.aspx?id={0}"
DataTextField=""
HeaderText=""
/>

<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="hlName" runat="server" NavigateUrl='<%# ("page.aspx?id=" + Eval("ID")) %>' />
</ItemTemplate>
</asp:TemplateField>

<asp:LinkButton
ID="lbButton"
CommandArgument='<%# Eval("ID") %>'
OnCommand="gvCommand_Command"
Text=""
runat="server"
/>

CONFIRM DELETE:

OnRowDataBound="GridView_RowDataBound"

<asp:TemplateField>
<ItemTemplate>

<asp:LinkButton
ID="lbDelete"
CommandArgument='<%# Eval("id") %>'
OnCommand="lbDelete_Command"
Text="Delete"
runat="server"
/>
</ItemTemplate>
</asp:TemplateField>

protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Attributes.Add("onmouseover", "Highlight(this);");
//e.Row.Attributes.Add("onmouseout", "resetColorRows();");

LinkButton lbDelete = (LinkButton)e.Row.FindControl("lbDelete");

if (lbDelete != null)
{
DataRowView drv = (DataRowView)e.Row.DataItem;

if (drv["Name"] != null)
lbDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete '" + drv["Name"].ToString().ToUpper() + "'');");
}
}
}

source

WriteToLog

static void WriteToLog(string strMsg)
{
string strFilename = "C:logsLog_"+System.DateTime.Now.ToString("MM-DD-YYYY")+".log";

FileStream fsLog = new FileStream(strFilename, FileMode.Append, FileAccess.Write, FileShare.Write);
StreamWriter swLog = new StreamWriter(fsLog);
swLog.Write(DateTime.Now.ToString() + " ");
swLog.WriteLine(strMsg);
swLog.Flush();
swLog.Close();
}

source

DataAccess

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Configuration;

DataAddUpdateDelete.Data_Insert(Convert.ToInt32(strGrantXMLID),
strGrantName,
strOrganization,
dtYear,
dAmount,
intDuration,
strPrimaryNTEE,
strSpecificNTEE,
strAddress1 + " " + strAddress2,
strCity,
strState,
strZipCode,
strPhone,
"0",
System.DateTime.Now,
"0",
System.DateTime.Now);

namespace DataAccess
{
public static class DataSelection
{

/// <summary>
/// Executes a stored procedure anda returns a datatable
/// </summary>
/// <param name="sp">This must be a stored procedure</param>
/// <returns>Data Table</returns>
public static DataTable ReturnDataTable(string sp)
{
return ReturnDataTable(sp, null);
}

/// <summary>
/// Executes a stored procedure anda returns a datatable
/// </summary>
/// <param name="sp">This must be a stored procedure</param>
/// <param name="Parameters">parameters to pass to stored procedure</param>
/// <returns>Data Table</returns>
public static DataTable ReturnDataTable(string sp, ListDictionary Parameters)
{
SqlConnection cnDBConn = new SqlConnection(ConfigurationSettings.AppSettings["DBConn"]);
SqlCommand cmdSPCommand = new SqlCommand();

try
{
cnDBConn.Open();
cmdSPCommand.Connection = cnDBConn;

cmdSPCommand.CommandText = sp;
cmdSPCommand.CommandType = CommandType.StoredProcedure;
IDataParameter p;

if (Parameters != null)
{
foreach (System.Collections.DictionaryEntry param in Parameters)
{
p = param.Key as IDataParameter;

if (null == p)
{
p.ParameterName = (string)param.Key;
p.Value = param.Value;
}
else
{
p.Value = param.Value;
}

cmdSPCommand.Parameters.Add(p);
}
}
SqlDataAdapter daAdapter = new SqlDataAdapter(cmdSPCommand);

DataTable dt = new DataTable();
daAdapter.Fill(dt);

return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cnDBConn.State == ConnectionState.Open)
cnDBConn.Close();
}

}
}

/// <summary>
/// This class contains all insert stored procedures
/// </summary>
public static class DataAddUpdateDelete
{

public static void Data_Insert(int GrantID,
string Grant_Name,
string Organization,
DateTime Year,
decimal Amount,
int Duration,
string Primary_NTEE,
string Specific_NTEE,
string Address,
string City,
string State,
string Zipcode,
string Phone,
string CreatedBy,
DateTime CreatedDate,
string ModifiedBy,
DateTime ModifiedDate
)
{
ListDictionary parameters = new ListDictionary();

parameters.Add(new SqlParameter("@GrantID", SqlDbType.Int, 0), GrantID);
parameters.Add(new SqlParameter("@Grant_Name", SqlDbType.NVarChar, 128), Grant_Name);
parameters.Add(new SqlParameter("@Organization", SqlDbType.NVarChar, 128), Organization);
parameters.Add(new SqlParameter("@Year", SqlDbType.DateTime, 0), Year);
parameters.Add(new SqlParameter("@Amount", SqlDbType.Money, 0), Amount);
parameters.Add(new SqlParameter("@Duration", SqlDbType.Int, 0), Duration);
parameters.Add(new SqlParameter("@Primary_NTEE", SqlDbType.NVarChar, 512), Primary_NTEE);
parameters.Add(new SqlParameter("@Specific_NTEE", SqlDbType.NVarChar, 512), Specific_NTEE);
parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 512), Address);
parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 128), City);
parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 64), State);
parameters.Add(new SqlParameter("@Zipcode", SqlDbType.NVarChar, 32), Zipcode);
parameters.Add(new SqlParameter("@Phone", SqlDbType.NVarChar, 32), Phone);
parameters.Add(new SqlParameter("@URL", SqlDbType.NVarChar, 32), "");
parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.NVarChar, 128), CreatedBy);
parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 0), CreatedDate);
parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.NVarChar, 128), ModifiedBy);
parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 0), ModifiedDate);

ExecuteStoredProcedure("sp_Insert", parameters,false);

}

/// <summary>
/// LoadFromSqlReader does not load data into your BusinessEntity
/// </summary>
/// <param name="sp">This must be a stored procedure</param>
/// <returns>The new Key field ID</returns>
public static int ExecuteStoredProcedure(string sp)
{
return ExecuteStoredProcedure(sp, null, CommandType.StoredProcedure, false);
}

/// <summary>
/// This version allows you to pass in Parameters and thier values
/// </summary>
/// <param name="sp">This must be a stored procedure</param>
/// <param name="Parameters">Two types of key/value pairs are allowed</param>
/// <param name="hasReturnValue">Indicates whether the item has a return value</param>
/// <returns>The new Key field ID</returns>
public static int ExecuteStoredProcedure(string sp, ListDictionary Parameters, bool hasReturnValue)
{
return ExecuteStoredProcedure(sp, Parameters, CommandType.StoredProcedure, hasReturnValue);
}

/// <summary>
/// This version allow you to use direct sql.
/// </summary>
/// <param name="sp">This must be a stored procedure</param>
/// <param name="Parameters">Two types of key/value pairs are allowed, see <see cref="LoadFromSql"/></param>
/// <param name="commandType">This property determines the type being passed in the "sp" parameter</param>
/// <param name="hasReturnValue">This boolean value indicates whether the call should return a key value from the call</param>
/// <returns>The new Key field ID</returns>
public static int ExecuteStoredProcedure(string sp, ListDictionary Parameters, CommandType commandType, bool hasReturnValue)
{
int intReturn = -1;
IDbCommand cmd;
cmd = new SqlCommand() as IDbCommand;
cmd.Connection = new SqlConnection() as IDbConnection;

try
{
cmd.CommandText = sp;
cmd.CommandType = commandType;
IDataParameter p;

if (Parameters != null)
{
foreach (System.Collections.DictionaryEntry param in Parameters)
{
p = param.Key as IDataParameter;

if (null == p)
{
p.ParameterName = (string)param.Key;
p.Value = param.Value;
}
else
{
p.Value = param.Value;
}

cmd.Parameters.Add(p);
}
}

if (hasReturnValue)
{
SqlParameter prmReturn = new SqlParameter("@Return", SqlDbType.Int);
prmReturn.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(prmReturn);
}

cmd.Connection.ConnectionString = ConfigurationSettings.AppSettings["DBConn"];
cmd.Connection.Open();
cmd.ExecuteNonQuery();

if (hasReturnValue)
{
// Get the out parameters
SqlParameter prmReturn = (SqlParameter)cmd.Parameters["@Return"];
intReturn = Convert.ToInt32(prmReturn.Value);
}

return intReturn;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
cmd.Connection.Close();
}
}

}
}

source

ASP.Net Page to Return an Image from an SQL Blob Query

protected void Page_Load(object sender, EventArgs e)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ProductCatalogueConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string blobId = Request.QueryString["ID"];
if (!string.IsNullOrEmpty(blobId))
{
string cmdText = "select A.blob from Core.Attachment A where A.AttachmentID = '" + blobId + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(cmdText, conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
byte[] imgBytes = (byte[])reader["blob"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imgBytes);
}
}
}

source

Fun with C# and HP Laserjet

namespace hphack
{
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class PrnHack
{
public static int Main(string[] args)
{
if(!ParseArgs(args))
{
return -1;
}

Console.WriteLine("
HP Display Hack");
Console.WriteLine("Host: {0}", args[0]);
Console.WriteLine("Message: {0}
", message);

IPEndPoint ipEndPoint;
ipEndPoint = new IPEndPoint( Dns.Resolve(args[0]).AddressList[0], PJL_PORT);

Console.WriteLine("Host is {0}", ipEndPoint.ToString());

Socket socket;
socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp
);

socket.Connect(ipEndPoint);

byte [] sendData;
string sendString;

sendString = String.Format(
"x1B%-12345X@PJL RDYMSG DISPLAY = "{0}"
x1B%-12345X
",
message
);

sendData = Encoding.ASCII.GetBytes(sendString);

int result;
result = socket.Send(sendData, sendData.Length, 0);

if(result == 0)
{
Console.WriteLine("Could not send on socket");
}

socket.Close();

Console.WriteLine("Finished

");
return 0;
}

protected static bool ParseArgs(string[] args)
{
if(args.Length != 2)
{
Console.WriteLine(
"HP Display Hack: " +
"hphack printername "message" "
);
return false;
}

if(args[1].Length > 16)
{
Console.WriteLine("Message must be <= 16 characters");
return false;
}

if(args[1].CompareTo("random") == 0)
{
message = GetRandomMessage();
}
else
{
message = args[1];
}

return true;
}

public static string GetRandomMessage()
{
string [] Messages = {
"BUZZ OFF",
"TOUCH ME",
"STEP AWAY",
"SET TO STUN",
"SCORE = 3413",
"PAT EATS MICE",
"FEED ME",
"GO AWAY",
"NEED MORE SPACE",
"POUR ME A DRINK",
"IN DISTRESS",
"NICE SHIRT",
"GO AWAY",
"NO PRINT FOR YOU",
"RADIATION LEAK",
"HANDS UP",
"PRESS MY BUTTON",
"TAKE ME HOME",
"LOOKS LIKE RAIN",
"HELLO WORLD",
"NICE HAIR",
"NEED A MINT?",
"BE GENTLE",
"BE KIND",
"INSERT DISK",
"BUY ME LUNCH",
"DONT STOP",
"COME CLOSER",
"TAKE A BREAK",
"INSERT QUARTER",
"BLACK SABBATH"
};

Random r = new Random();
return Messages[r.Next() % Messages.Length];
}

protected const int PJL_PORT = 9100;
protected static string message = "NO MESSAGE";

}
}

source

GCC inline Assembly template

asm(".intel_syntax
"
"
"
"
"
".att_syntax
"
:
:
);

source