Implement queue using 2 stacks - javascript

Can anyone tell me. how to implement queue using 2 stacks.
Specifically, implement the enqueue and dequeuer methods.
it will helpful if you guys tell me in php or JavaScript programming

Here is a personal example, I'm sure it could be more optimized, but it allows for queue dequeue and peek functionality in JS.
function processData(input) {
let stackOne = [];
let stackTwo = [];
let parsableInput = input.split('\n');
for(let i = 1; i < parsableInput.length; i++) {
// handle 1 push
if (parsableInput[i][0] === '1') {
enqueue(stackOne, stackTwo, parsableInput[i].slice(2));
}
// handle 2
if (parsableInput[i] === '2') {
dequeue(stackTwo);
}
// handle 3
if (parsableInput[i] === '3') {
console.log(peek(stackTwo));
}
}
}
function enqueue(stackOne, stackTwo, queuedValue) {
while(stackTwo.length !== 0) {
stackOne.push(stackTwo.pop());
}
stackOne.push(queuedValue);
while(stackOne.length !== 0) {
stackTwo.push(stackOne.pop());
}
}
function dequeue(stackTwo) {
return stackTwo.pop();
}
function peek(stackTwo) {
let stringToBeParsed = stackTwo[stackTwo.length - 1];
let parsedString = stringToBeParsed.slice(0, stringToBeParsed.length);
if (parsedString) {
return parsedString;
} else {
console.log('Error: there is nothing to peek at!');
}
}

Here is my solution, but it's in C lang.
#include<stdio.h>
#include<stdlib.h>
struct Stack{
int size;
int top;
int *S;
}S1,S2;
void create(struct Stack *st){
st->size=10;
st->top=-1;
st->S=(int *)malloc(st->size*sizeof(int));
}
void push(struct Stack *st, int x){
if(st->top==st->size-1)
printf("\nStack overflow\n");
else
{
st->top++;
st->S[st->top]=x;
}
}
int pop(struct Stack *st){
int x=-1;
if(st->top==-1)
printf("\nStack Underflow\n");
else
{
x=st->S[st->top--]; // post decrement of top
}
return x;
}
int isEmpty(struct Stack *st){
if(st->top==-1)
return 1;
return 0;
}
void enqueue(int x){
push(&S1,x);
}
int dequeue(){
int x=-1;
if(isEmpty(&S2)){
if(isEmpty(&S1)){
printf("Empty Queue!");
return x;
}
else
{
while(!isEmpty(&S1))
push(&S2,pop(&S1));
}
}
return pop(&S2);
}
void display(struct Stack *st){
for(int i=st->top;i>=0;i--)
printf("%d ",st->S[i]);
printf("\n");
}
int main(){
create(&S1);
create(&S2);
enqueue(10);
enqueue(20);
enqueue(30);
enqueue(40);
int deleted_element=dequeue();
printf("Dequeued Element is = %d\n",deleted_element);
display(&S2);
return 0;
}

Related

How can I develop a script with frida to intercept when it's encrypted?

I have a problem where I can't develop Scripts for frida with javascript, I would like a base to intercept the function in which it returns anything from a class com.example.utils:
`public class utils {
public static String error;
public static void onCreate() {
GetError();
}
public static Activity getActivity() {
return UnityPlayer.currentActivity;
}
public static void print(String str) {
if (Functions.isDebug) {
Log.i(AdColonyAppOptions.UNITY, str);
}
}
public static void GetError() {
StackTraceElement[] stackTrace;
try {
throw new Exception();
} catch (Exception e) {
error = String.valueOf(error) + e.getMessage();
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
error = String.valueOf(error) + stackTraceElement.getClassName() + "->" + stackTraceElement.getMethodName() + "\n";
}
print(error);
}
}
public static boolean isDebuggable() {
return (getActivity().getApplicationContext().getApplicationInfo().flags & 2) != 0 || Debug.isDebuggerConnected();
}
public static String XOR(String str, String str2, boolean z) {
if (z) {
try {
return Base64.encodeToString(EncryptDecrypt(str.getBytes(C.UTF8_NAME), str2.getBytes(C.UTF8_NAME)), 0);
} catch (UnsupportedEncodingException unused) {
return "";
}
}
try {
return new String(EncryptDecrypt(Base64.decode(str, 0), str2.getBytes(C.UTF8_NAME)), C.UTF8_NAME);
} catch (UnsupportedEncodingException unused2) {
return "";
}
}
private static byte[] EncryptDecrypt(byte[] bArr, byte[] bArr2) {
int length = bArr2.length;
int length2 = bArr.length;
byte[] bArr3 = new byte[256];
for (int i = 0; i < 256; i++) {
bArr3[i] = (byte) i;
}
int i2 = 0;
for (int i3 = 0; i3 < 256; i3++) {
i2 = (((i2 + bArr3[i3]) + bArr2[i3 % length]) % 256) & 255;
byte b = bArr3[i3];
bArr3[i3] = bArr3[i2];
bArr3[i2] = b;
}
int i4 = 0;
int i5 = 0;
for (int i6 = 0; i6 < length2; i6++) {
i4 = ((i4 + 1) % 256) & 255;
i5 = ((i5 + bArr3[i4]) % 256) & 255;
byte b2 = bArr3[i4];
bArr3[i4] = bArr3[i5];
bArr3[i5] = b2;
bArr[i6] = (byte) (bArr3[((bArr3[i4] + bArr3[i5]) % 256) & 255] ^ bArr[i6]);
}
return bArr;
}
}
How can I develop a script with frida to intercept when it's encrypted?
I tried to write codes but it always went wrong, please help me
The following script should intercept the EncryptDecrypt method of the code you have posted and print the return value as hex encoded string:
Java.perform(() => {
let testClass = Java.use('com.example.utils');
let methodToHook = testClass.EncryptDecrypt.overload('[B', '[B');
methodToHook.implementation = function (arg1, arg2) {
console.log('EncryptDecrypt called');
console.log('EncryptDecrypt arg1 = ' + encodeHex(arg1));
console.log('EncryptDecrypt arg2 = ' + encodeHex(arg2));
let retVal = methodToHook.call(testClass, arg1, arg2);
console.log(encodeHex(retVal));
};
function encodeHex(byteArray) {
const HexClass = Java.use('org.apache.commons.codec.binary.Hex');
const StringClass = Java.use('java.lang.String');
const hexChars = HexClass.encodeHex(byteArray);
return StringClass.$new(hexChars).toString();
}
});
The encodeHex function is necessary as in Java calling toString() of a byte[] does not print the content, but just the internal object reference - and I assume the content of the byte array is what you want to view. encodeHex will only work if you are on Android or the Java application you hook includes Apache commons codec library.
If you don't know how to hook a method you can use a short-curt: Load the APK in jadx-gui, select the method you want to hook and select Copy as frida snippet from the context menu. This will generate a short JavaScript snippet you can copy into your Frida script.

Overflow & Underflow

I am trying to figure out the solution but I can't find it. I need a function that throws an error when maximum call stack is reached and throws an error when minimum call stack is reached.
class Stack {
constructor() {
this.items = [];`Please Help me with this...`
}
push(item) {
this.items.push(item)
}
pop() {
const popped = this.items.pop();
if (this.items == null) {
throw new Error("Underflow");
}
return popped;
}
isEmpty() {
}
peek() {
}
}
How about modifying your functions?
push and pop should throw an error if Number.MAX_SAFE_INTEGER or <= 0 is reached.
class Stack {
constructor() {
this.items = [];
}
push(item) {
if (this.items.length >= Number.MAX_SAFE_INTEGER) {
throw new Error("Maximum call stack reached");
}
this.items.push(item)
}
pop() {
if (this.items.length <= 0) {
throw new Error("Minimum call stack reached");
}
return this.items.pop();
}
isEmpty() {
return this.items.length === 0;
}
peek() {
return this.items[this.items.length - 1];
}
}

How to save last searched when using search on input?

I am trying to write an algorithm that saves the recently searched keywords. The issue is that the user is not triggering the search but instead the search is being triggered every time something is typed. Currently, I am trying to save the last searched keyword and checking if the next one starts with the last one in order to discard the last one.
async _persistSearch(term) {
const serachLog = await this._getLastSearchedFile()
console.log("[SEARCH]", serachLog);
if (Object.keys(serachLog) == 0) {
serachLog.searches = [term];
serachLog.lastUpdated = Date.now()
} else if (term.startsWith(this.lastSearhed)) {
const toPersist = serachLog.searches.filter((value) => value != this.lastSearhed).push(term);
serachLog.searches = toPersist;
} else {
serachLog.searches.push(term);
}
this.lastSearhed = term;
await writeJSONFile(this.searchesFile, serachLog);
}
For example for an input [so, som, some, somet, someth,somethi, somethin, something, somethin] to be [something]
You should use Trie(Prefix Tree) to save searched keywords. Say you are only dealing with lower-case English letters, then each node can have up to 26 children nodes. For each new search keyword, call the startsWith method to check if this new keyword is any prefix of the previous keywords.
Read about this https://en.wikipedia.org/wiki/Trie if you need more explanations about why a Trie should be used in your case.
A java implementation of this data structure is as following.
class Trie {
class TrieNode{
private char c;
private Map<Character, TrieNode> map;
private boolean isLeaf;
TrieNode() {
this.map = new HashMap<>();
}
TrieNode(char c) {
this.c = c;
this.map = new HashMap<>();
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode currNode = root;
for(int i = 0; i < word.length(); i++) {
char currChar = word.charAt(i);
if(!currNode.map.containsKey(currChar)) {
TrieNode newNode = new TrieNode(currChar);
currNode.map.put(currChar, newNode);
currNode = newNode;
}
else {
currNode = currNode.map.get(currChar);
}
if(i == word.length() - 1) {
currNode.isLeaf = true;
}
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode currNode = root;
for(int i = 0; i < word.length(); i++) {
if(!currNode.map.containsKey(word.charAt(i))) {
return false;
}
currNode = currNode.map.get(word.charAt(i));
if( i == word.length() - 1 && !currNode.isLeaf) {
return false;
}
}
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode currNode = root;
for(int i = 0; i < prefix.length(); i++) {
if(!currNode.map.containsKey(prefix.charAt(i))) {
return false;
}
currNode = currNode.map.get(prefix.charAt(i));
}
return true;
}
}

1120: Access of undefined property (With 8 Errors)

I am a university student currently doing a project on a game on AS3
When i run my game i get 8 errors regarding "1120: Access of undefined property...." I don't know what I'm doing wrong so can anyone help me with this?
here is my code(yeah i know its long):
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
public class PlatformGamess extends MovieClip {
// movement constants
static const gravity:Number=.004;
// screen constants
static const edgeDistance:Number=100;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String="start";
private var playerLives:int;
private var lastTime:Number=0;
// start game
public function startPlatformGamess(){
playerObjects=new Array();
gameScore=0;
gameMode="play";
playerLives=3;
}
public function startGameLevel(){
createHero();
addEnemies();
examineLevel();
this.addEventListener(Event.ENTER_FRAME,gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gameMode="play";
addScore(0);
showLives();
}
// creates the hero object and sets all properties
public function createHero() {
hero=new Object();
hero.mc=gamelevel.hero;
hero.inAir=false;
hero.direction=1;
hero.animstate="stand";
hero.walkAnimation=new Array(2)
hero.animstep=0;
hero.jump=false;
hero.moveLeft=false;
hero.moveRight=false;
hero.jumpSpeed=.8;
hero.walkSpeed=.15;
hero.width=20.0;
hero.height=40.0;
hero.startx=hero.mc.x;
hero.starty=hero.mc.y;
}
public function addEnemies() {
enemies = new Array();
var i:int=1;
while (true) {
if (gamelevel["enemy"+i]==null) break;
var enemy=new Object();
enemy.mc=gamelevel["enemy"+i];
enemy.dx=0.0;
enemy.dy=0.0;
enemy.inAir=false;
enemy.direction=1;
enemy.animstate="stand"
enemy.walkAnimation = new Array(2);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
}
}
public function examineLevel(){
fixedObjects=new Array();
otherObject=new Array();
for (var i:int=0;i<this.gamelevel.numChildren;i++) {
var mc=this.gamelevel.getChildAt(i);
if ((mc is Floor) || (mc is Wall)) {
var floorObjects:Object=new Object();
floorObject.mc=mc;
floorObject.leftside=mc.x;
floorObject.rightside=mc.x+mc.width;
floorObject.topside.mc.y;
floorObject.bottomside=mc.y+mc.height;
fixedObjects.push(floorObject);
} else if ((mc is Treasure) || (mc is Key) ||
(mc is Door) || (mc is Chest)) {
otherObjects.push(mc);
}
}
}
public function keyDownFunction(event:KeyboardEvent) {
if (gamemode != "play") return; // don't move until in play mode
if (event.keyCode==37){
hero.moveLeft=true;
} else if (event.keyCode==39) {
hero.moveRight==true;
} else if (event.keyCode==32){
if (!hero.inAir){
hero.jump=true;
}
}
}
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
hero.moveLeft = false;
} else if (event.keyCode == 39) {
hero.moveRight = false;
}
}
public function gameLoop(event:Event) {
if (lastTime==0)lastTime=getTimer();
var timeDiff:int=getTimer()-lastTime;
lastTime+=timeDiff;
if (gameMode=="play"){
moveCharacter(hero,timeDiff);
moveEnemies(timeDiff);
checkCollisions();
scrollWithHero();
}
}
// loop through all enemies and move them
public function moveEnemies(timeDiff:int) {
for(var i:int=0;i<enemies.length;i++) {
// move
moveCharacter(enemies[i],timeDiff);
// if hit a wall, turn around
if (enemies[i].hitWallRight) {
enemies[i].moveLeft=true;
enemies[i].moveRight=false;
} else if (enemies[i].hitWallLeft) {
enemies[i].moveLeft=false;
enemies[i].moveRight=true;
}
}
}
public function moveCharacter(char:Object,timeDiff:Number) {
if (timeDiff < 1) return;
var verticalChange:Number=char.dy*timeDiff+timeDiff*gravity;
if (verticalChange>15.0) verticalChange=15.0;
char.dy+=timeDiff*gravity;
var horizontalChange=0;
var newAnimState:String="stand";
var newDirection:int=char.direction;
if (char.moveLeft){
// wa
horizontalChange = -char.walkSpeed*timeDiff;
newAnimState="walk";
newDirection=-1;
} else if (char.moveRight){
// walk right
horizontalChange = char.walkSpeed*timeDiff;
newAnimState="walk";
newDirection=1;
}
if (char.jump) {
// start jump
char.jump = false;
char.dy = -char.jumpSpeed;
verticalChange = -char.jumpSpeed;
newAnimState = "jump";
}
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for(var i:int=0;i<fixedObjects.length;i++) {
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside)) {
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside)) {
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
}
}
}
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for(i=0;i<fixedObjects.length;i++) {
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside)) {
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside)) {
newX = fixedObjects[i].rightside+char.width/2;
char.hitWallLeft = true;
break;
}
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside)) {
newX = fixedObjects[i].leftside-char.width/2;
char.hitWallRight = true;
break;
}
}
}
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir) {
newAnimState = "jump";
}
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk") {
char.animstep += timeDiff/60;
if (char.animstep > char.walkAnimation.length) {
char.animstep = 0;
}
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
} else {
char.mc.gotoAndStop(char.animstate);
}
// changed directions
if (newDirection != char.direction) {
char.direction = newDirection;
char.mc.scaleX = char.direction;
}
}
public function scrollWithHero(){
var stagePosition:Number = gamelevel.x+hero.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge){
gamelevel.x -= (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth)) gamelevel.x = -(gamelevel.width-stage.stageWidth);
}
if (stagePosition < leftEdge){
gamelevel.x += (leftEdge-stagePosition);
if (gamelevel.x > 0)gamelevel.x=0;
}
}
public function checkCollisions(){
// enemies
for(var i:int=enemies.length-1;i>=0;i--){
if (hero.mc.hitTestObject(enemies[i].mc)){
if (hero.inAir && (hero.dy>0)){
enemyDie(i);
} else {
heroDie();
}
}
}
for(i=otherObjects.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(otherObjects[i])) {
getObject(i);
}
}
}
public function enemyDie(enemyNum:int) {
var pb:PointBurst = new PointBurst(gamelevel,"Zetsu Extinct!",enemies[enemyNum].mc.x,enemies[enemyNum].mc.y-20);
gamelevel.removeChild(enemies[enemyNum].mc);
enemies.splice(enemyNum,1);
}
public function heroDie() {
// show dialog box
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
if (playerLives == 0) {
gameMode = "gameover";
dialog.message.text = "Game Over!";
} else {
gameMode = "dead";
dialog.message.text = "Yoi Failed...";
playerLives--;
}
hero.mc.gotoAndPlay("die");
}
public function getObject(objectNum:int) {
if (otherObjects[objectNum] is Treasure) {
var pb:PointBurst = new PointBurst(gamelevel,100,otherObjects[objectNum].x,otherObjects[objectNum].y);
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
addScore(100);
} else if (otherObjects[objectNum] is Key) {
pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
} else if (otherObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return;
if (otherObjects[objectNum].currentFrame == 1) {
otherObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
} else if (otherObjects[objectNum] is Chest) {
otherObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
public function addScore(numPoints:int) {
gameScore += numPoints;
scoreDisplay.text = String(gameScore);
}
// update player lives
public function showLives() {
livesDisplay.text = String(playerLives);
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
showLives();
hero.mc.x = hero.startx;
hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
}
}
}
here are the list of errors in the coding:
*Line 103, Column 4 1120: Access of undefined property otherObject.
*Line 109, Column 6 1120: Access of undefined property floorObject.
*Line 110, Column 6 1120: Access of undefined property floorObject.
*Line 111, Column 6 1120: Access of undefined property floorObject.
*Line 112, Column 6 1120: Access of undefined property floorObject.
*Line 113, Column 6 1120: Access of undefined property floorObject.
*Line 114, Column 24 1120: Access of undefined property floorObject.
*Line 124, Column 8 1120: Access of undefined property gamemode.
can please someone help me with this i have been scratching my head over it forever
thanks
Your code is full of typos.ActionScript is case-sensitive, and variables need to be spelled correctly!
Line 103:Change otherObject=new Array(); to otherObjects=new Array();
Line 108:Change var floorObjects:Object=new Object(); to var floorObject:Object=new Object();
Line 124:Change if (gamemode != "play") to if (gameMode != "play")

ActiveX C++ control WriteFile fails after 4 attempts

I have an ActiveX HTML object written in C++. The code is used to print to a bluetooth printer. I am able to make 4 successful calls to the code (shown below) and then the "WriteFile" function starts returning "0". When I shut down the browser and open it up again, it works for another 4 trys... so this sure seems like a memory leak or something, but i'm not very good with C++ unfortunately... so here i am for some help :)
BOOL RegGetValue(HKEY hRootKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbDataLen)
{
LRESULT lResult = -1;
HKEY hKey = NULL;
lResult =RegOpenKeyEx(hRootKey, lpSubKey, 0, 0, &hKey);
int e = GetLastError();
if (lResult == ERROR_SUCCESS)
{
lResult = RegQueryValueEx(hKey, lpValueName, NULL, lpType, lpData, lpcbDataLen);
e = GetLastError();
RegCloseKey(hKey);
}
return (lResult == ERROR_SUCCESS);
}
#define MSS_PORTS_BASE _T("Software\\Microsoft\\Bluetooth\\Serial\\Ports")
bool FindBluetoothPort(TCHAR name[16])
{
HKEY hKey, hRoot;
TCHAR szPort[20] = _T(""), szPortString[20];
DWORD len, dwIndex=0;
bool bFound=false;
INT i = 0, rc;
DWORD dwNSize;
DWORD dwCSize;
TCHAR szClass[256];
TCHAR szName[MAX_PATH];
FILETIME ft;
hRoot = HKEY_LOCAL_MACHINE;
if (RegOpenKeyEx (hRoot, MSS_PORTS_BASE, 0, 0, &hKey) != ERROR_SUCCESS)
{ rc = GetLastError();
return 0;
}
dwNSize = dim(szName);
dwCSize = dim(szClass);
rc = RegEnumKeyEx (hKey, i, szName, &dwNSize, NULL, szClass, &dwCSize, &ft);
while (rc == ERROR_SUCCESS)
{
// how many children
TCHAR szCurrentKey[MAX_PATH];
wcscpy(szCurrentKey, MSS_PORTS_BASE);
wcscat(szCurrentKey, TEXT("\\"));
wcscat(szCurrentKey, szName);
wcscat(szCurrentKey, TEXT("\\"));
len = sizeof(szPort);
if(RegGetValue(hRoot, szCurrentKey, _T("Port"), NULL, (LPBYTE)szPort, &len))
{
wsprintf(szPortString, _T("%s:"), szPort);
bFound = true;
break;
}
dwNSize = dim(szName);
rc = RegEnumKeyEx(hKey, ++i, szName, &dwNSize, NULL, NULL, 0, &ft);
}
if(bFound)
_tcscpy(name, szPortString);
return bFound;
}
WriteFile(
HANDLE hFile,
__in_bcount(nNumberOfBytesToWrite) LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
void CHSMBTPrintXCtrl::PrintLabel(void)
{
//MessageBox(TEXT("Started"), TEXT("HSMBTPrintX"), MB_OK);
TCHAR g_szComPort[16];
char szout[900];
TCHAR comPort[16];
HANDLE hCom;
unsigned long bytesWritten;
int counter;
for (counter = 0; counter < 900; counter++)
szout[counter] = NULL;
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (!FindBluetoothPort(g_szComPort))
{
MessageBox(TEXT("No Port Found"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
//Try at least 3 times to get a valid handle
for(counter = 0; counter < 2; ++counter)
{
hCom = CreateFile(g_szComPort,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (hCom)
break;
}
if (hCom == NULL)
{
MessageBox(TEXT("Could not open file to print"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
CT2CA date(COleDateTime::GetCurrentTime().Format(L"%m/%d/%y"));
CT2CA time(COleDateTime::GetCurrentTime().Format(L"%H:%M"));
if (m_actionParameter == "SKUTagPrint") {
CT2CA department (m_departmentParameter);
CT2CA sku (m_skuParameter);
for (counter = 0; counter < 900; counter++)
szout[counter] = NULL;
strcpy(szout, "^XA\n");
strcat(szout, "SomeTextHere");
//more strcat lines here
if(WriteFile(hCom,szout,900,&bytesWritten,NULL)==0) {
MessageBox(TEXT("Unable to write file"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
}
// MessageBox(m_barcodeParameter, TEXT("HSMBTPrintX"), MB_OK);
// Create text to send to printer
FireLabelPrinted();
return;
}
// HTML
<object id="HSMBTPrintX1" width="350" height="350"
classid="CLSID:68D05400-18A6-4B39-B3FF-A17D77C1EDDF"
codebase=".\..\HSMBTPrintX.ocx#1,0,0,1" style="display:none;">
</object>
<script type="text/javascript" for="HSMBTPrintX1" event="LabelPrinted()">
alert('Label(s) successfully printed.');
</script>
// Javascript
HSMBTPrintX1.sizeParameter = document.getElementById("tdSize").innerText;
HSMBTPrintX1.actionParameter = "SKUTagPrint";
HSMBTPrintX1.PrintLabel();
You need to match a CreateFile() with a CloseHandle() or odd things can happen, see: http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx

Categories

Resources