code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <map>
#include <vector>
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
extern NPClass GenericNPObjectClass;
typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
struct ltnum
{
bool operator()(long n1, long n2) const
{
return n1 < n2;
}
};
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
class GenericNPObject: public NPObject
{
private:
GenericNPObject(const GenericNPObject &);
bool invalid;
DefaultInvoker defInvoker;
void *defInvokerObject;
std::vector<NPVariant> numeric_mapper;
// the members of alpha mapper can be reassigned to anything the user wishes
std::map<const char *, NPVariant, ltstr> alpha_mapper;
// these cannot accept other types than they are initially defined with
std::map<const char *, NPVariant, ltstr> immutables;
public:
friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *);
GenericNPObject(NPP instance);
GenericNPObject(NPP instance, bool isMethodObj);
~GenericNPObject();
void Invalidate() {invalid = true;}
void SetDefaultInvoker(DefaultInvoker di, void *context) {
defInvoker = di;
defInvokerObject = context;
}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) {
return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result);
}
static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (((GenericNPObject *)npobj)->defInvoker) {
return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result);
}
else {
return false;
}
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((GenericNPObject *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((GenericNPObject *)npobj)->SetProperty(name, value);
}
static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->RemoveProperty(name);
}
static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) {
return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount);
}
bool HasMethod(NPIdentifier name);
bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result);
bool HasProperty(NPIdentifier name);
bool GetProperty(NPIdentifier name, NPVariant *result);
bool SetProperty(NPIdentifier name, const NPVariant *value);
bool RemoveProperty(NPIdentifier name);
bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount);
};
| 007slmg-ff | ff-activex-host/ffactivex/GenericNPObject.h | C++ | lgpl | 5,100 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
// TODO: reference additional headers your program requires here
| 007slmg-ff | ff-activex-host/ffactivex/stdafx.h | C | lgpl | 2,218 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winreg.h>
#include "ffactivex.h"
#include "common/stdafx.h"
#include "axhost.h"
#include "atlutil.h"
#include "authorize.h"
// ----------------------------------------------------------------------------
#define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/ffactivex\\MimeTypes\\application/x-itst-activex"
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId);
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId);
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value);
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType);
// ---------------------------------------------------------------------------
HKEY BaseKeys[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
// ----------------------------------------------------------------------------
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType)
{
BOOL ret = FALSE;
NPObject *globalObj = NULL;
NPIdentifier identifier;
NPVariant varLocation;
NPVariant varHref;
bool rc = false;
int16 i;
char *wrkHref;
#ifdef NDEF
_asm{int 3};
#endif
if (Instance == NULL) {
return (FALSE);
}
// Determine owning document
// Get the window object.
NPNFuncs.getvalue(Instance,
NPNVWindowNPObject,
&globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(Instance,
globalObj,
identifier,
&varLocation);
NPNFuncs.releaseobject(globalObj);
if (!rc){
log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(Instance,
locationObj,
identifier,
&varHref);
NPNFuncs.releasevariantvalue(&varLocation);
if (!rc) {
log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property");
return false;
}
ret = TRUE;
wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1);
memcpy(wrkHref,
varHref.value.stringValue.UTF8Characters,
varHref.value.stringValue.UTF8Length);
wrkHref[varHref.value.stringValue.UTF8Length] = 0x00;
NPNFuncs.releasevariantvalue(&varHref);
for (i = 0;
i < ArgC;
++i) {
// search for any needed information: clsid, event handling directives, etc.
if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CLSID,
wrkHref,
ArgV[i]);
} else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) {
// The class id of the control we are asked to load
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_PROGID,
wrkHref,
ArgV[i]);
} else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CODEBASEURL,
wrkHref,
ArgV[i]);
}
}
log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False");
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId)
{
USES_CONVERSION;
BOOL ret;
ret = TestExplicitAuthorization(A2W(MimeType),
A2W(AuthorizationType),
A2W(DocumentUrl),
A2W(ProgramId));
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId)
{
BOOL ret = FALSE;
#ifndef NO_REGISTRY_AUTHORIZE
HKEY hKey;
HKEY hSubKey;
ULONG i;
ULONG j;
ULONG keyNameLen;
ULONG valueNameLen;
wchar_t keyName[_MAX_PATH];
wchar_t valueName[_MAX_PATH];
if (DocumentUrl == NULL) {
return (FALSE);
}
if (ProgramId == NULL) {
return (FALSE);
}
#ifdef NDEF
MessageBox(NULL,
DocumentUrl,
ProgramId,
MB_OK);
#endif
if ((hKey = FindKey(MimeType,
AuthorizationType)) != NULL) {
for (i = 0;
!ret;
i++) {
keyNameLen = sizeof(keyName);
if (RegEnumKey(hKey,
i,
keyName,
keyNameLen) == ERROR_SUCCESS) {
if (WildcardMatch(keyName,
DocumentUrl)) {
if (RegOpenKeyEx(hKey,
keyName,
0,
KEY_QUERY_VALUE,
&hSubKey) == ERROR_SUCCESS) {
for (j = 0;
;
j++) {
valueNameLen = sizeof(valueName);
if (RegEnumValue(hSubKey,
j,
valueName,
&valueNameLen,
NULL,
NULL,
NULL,
NULL) != ERROR_SUCCESS) {
break;
}
if (WildcardMatch(valueName,
ProgramId)) {
ret = TRUE;
break;
}
}
RegCloseKey(hSubKey);
}
if (ret) {
break;
}
}
} else {
break;
}
}
RegCloseKey(hKey);
}
#endif
return (ret);
}
// ----------------------------------------------------------------------------
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value)
{
size_t i;
size_t j = 0;
size_t maskLen;
size_t valueLen;
maskLen = wcslen(Mask);
valueLen = wcslen(Value);
for (i = 0;
i < maskLen + 1;
i++) {
if (Mask[i] == '?') {
j++;
continue;
}
if (Mask[i] == '*') {
for (;
j < valueLen + 1;
j++) {
if (WildcardMatch(Mask + i + 1,
Value + j)) {
return (TRUE);
}
}
return (FALSE);
}
if ((j <= valueLen) &&
(Mask[i] == tolower(Value[j]))) {
j++;
continue;
}
return (FALSE);
}
return (TRUE);
}
// ----------------------------------------------------------------------------
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType)
{
HKEY ret = NULL;
HKEY plugins;
wchar_t searchKey[_MAX_PATH];
wchar_t pluginName[_MAX_PATH];
DWORD j;
size_t i;
for (i = 0;
i < ARRAYSIZE(BaseKeys);
i++) {
if (RegOpenKeyEx(BaseKeys[i],
L"SOFTWARE\\MozillaPlugins",
0,
KEY_ENUMERATE_SUB_KEYS,
&plugins) == ERROR_SUCCESS) {
for (j = 0;
ret == NULL;
j++) {
if (RegEnumKey(plugins,
j,
pluginName,
sizeof(pluginName)) != ERROR_SUCCESS) {
break;
}
wsprintf(searchKey,
L"%s\\MimeTypes\\%s\\%s",
pluginName,
MimeType,
AuthorizationType);
if (RegOpenKeyEx(plugins,
searchKey,
0,
KEY_ENUMERATE_SUB_KEYS,
&ret) == ERROR_SUCCESS) {
break;
}
ret = NULL;
}
RegCloseKey(plugins);
if (ret != NULL) {
break;
}
}
}
return (ret);
}
| 007slmg-ff | ff-activex-host/ffactivex/authorize.cpp | C++ | lgpl | 10,024 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <atlbase.h>
#include <atlsafe.h>
#include <npapi.h>
#include <npfunctions.h>
#include <prtypes.h>
#include <npruntime.h>
#include "scriptable.h"
#include "GenericNPObject.h"
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
BSTR
Utf8StringToBstr(LPCSTR szStr, int iSize)
{
BSTR bstrVal;
// Chars required for string
int iReq = 0;
if (iSize > 0) {
if ((iReq = MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, 0, 0)) == 0) {
return (0);
}
}
// Account for terminating 0.
if (iReq != -1) {
++iReq;
}
if ((bstrVal = ::SysAllocStringLen(0, iReq)) == 0) {
return (0);
}
memset(bstrVal, 0, iReq * sizeof(wchar_t));
if (iSize > 0) {
// Convert into the buffer.
if (MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, bstrVal, iReq) == 0) {
::SysFreeString(bstrVal);
return 0;
}
}
return (bstrVal);
}
void
BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance)
{
USES_CONVERSION;
char *npStr = NULL;
size_t sourceLen;
size_t bytesNeeded;
sourceLen = lstrlenW(bstr);
bytesNeeded = WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
NULL,
0,
NULL,
NULL);
bytesNeeded += 1;
// complete lack of documentation on Mozilla's part here, I have no
// idea how this string is supposed to be freed
npStr = (char *)NPNFuncs.memalloc(bytesNeeded);
if (npStr) {
memset(npStr, 0, bytesNeeded);
WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
npStr,
bytesNeeded - 1,
NULL,
NULL);
STRINGZ_TO_NPVARIANT(npStr, (*npvar));
}
else {
STRINGZ_TO_NPVARIANT(NULL, (*npvar));
}
}
void
Dispatch2NPVar(IDispatch *disp, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
((Scriptable *)obj)->setControl(disp);
((Scriptable *)obj)->setInstance(instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
void
Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
((Scriptable *)obj)->setControl(unk);
((Scriptable *)obj)->setInstance(instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
NPObject *
SafeArray2NPObject(SAFEARRAY *parray, unsigned short dim, unsigned long *pindices, NPP instance)
{
unsigned long *indices = pindices;
NPObject *obj = NULL;
bool rc = true;
if (!parray || !instance) {
return NULL;
}
obj = NPNFuncs.createobject(instance, &GenericNPObjectClass);
if (NULL == obj) {
return NULL;
}
do {
if (NULL == indices) {
// just getting started
SafeArrayLock(parray);
indices = (unsigned long *)calloc(1, parray->cDims * sizeof(unsigned long));
if (NULL == indices) {
rc = false;
break;
}
}
NPIdentifier id = NULL;
NPVariant val;
VOID_TO_NPVARIANT(val);
for(indices[dim] = 0; indices[dim] < parray->rgsabound[dim].cElements; indices[dim]++) {
if (dim == (parray->cDims - 1)) {
// single dimension (or the bottom of the recursion)
if (parray->fFeatures & FADF_VARIANT) {
VARIANT variant;
VariantInit(&variant);
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &variant))) {
rc = false;
break;
}
Variant2NPVar(&variant, &val, instance);
VariantClear(&variant);
}
else if (parray->fFeatures & FADF_BSTR) {
BSTR bstr;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &bstr))) {
rc = false;
break;
}
BSTR2NPVar(bstr, &val, instance);
}
else if (parray->fFeatures & FADF_DISPATCH) {
IDispatch *disp;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &disp))) {
rc = false;
break;
}
Dispatch2NPVar(disp, &val, instance);
}
else if (parray->fFeatures & FADF_UNKNOWN) {
IUnknown *unk;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &unk))) {
rc = false;
break;
}
Unknown2NPVar(unk, &val, instance);
}
}
else {
// recurse
NPObject *o = SafeArray2NPObject(parray, dim + 1, indices, instance);
if (NULL == o) {
rc = false;
break;
}
OBJECT_TO_NPVARIANT(o, val);
}
id = NPNFuncs.getintidentifier(parray->rgsabound[dim].lLbound + indices[dim]);
// setproperty will call retainobject or copy the internal string, we should
// release variant
NPNFuncs.setproperty(instance, obj, id, &val);
NPNFuncs.releasevariantvalue(&val);
VOID_TO_NPVARIANT(val);
}
} while (0);
if (false == rc) {
if (!pindices && indices) {
free(indices);
indices = NULL;
SafeArrayUnlock(parray);
}
if (obj) {
NPNFuncs.releaseobject(obj);
obj = NULL;
}
}
return obj;
}
#define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val))
void
Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
SAFEARRAY *parray = NULL;
if (!var || !npvar) {
return;
}
VOID_TO_NPVARIANT(*npvar);
switch (var->vt & ~VT_BYREF) {
case VT_EMPTY:
VOID_TO_NPVARIANT((*npvar));
break;
case VT_NULL:
NULL_TO_NPVARIANT((*npvar));
break;
case VT_LPSTR:
// not sure it can even appear in a VARIANT, but...
STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar));
break;
case VT_BSTR:
BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance);
break;
case VT_I1:
INT32_TO_NPVARIANT((int32)GETVALUE(var, cVal), (*npvar));
break;
case VT_I2:
INT32_TO_NPVARIANT((int32)GETVALUE(var, iVal), (*npvar));
break;
case VT_I4:
INT32_TO_NPVARIANT((int32)GETVALUE(var, lVal), (*npvar));
break;
case VT_UI1:
INT32_TO_NPVARIANT((int32)GETVALUE(var, bVal), (*npvar));
break;
case VT_UI2:
INT32_TO_NPVARIANT((int32)GETVALUE(var, uiVal), (*npvar));
break;
case VT_UI4:
INT32_TO_NPVARIANT((int32)GETVALUE(var, ulVal), (*npvar));
break;
case VT_BOOL:
BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar));
break;
case VT_R4:
DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar));
break;
case VT_R8:
DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar));
break;
case VT_DISPATCH:
Dispatch2NPVar(GETVALUE(var, pdispVal), npvar, instance);
break;
case VT_UNKNOWN:
Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance);
break;
case VT_CY:
DOUBLE_TO_NPVARIANT((double)GETVALUE(var, cyVal).int64 / 10000, (*npvar));
break;
case VT_DATE:
BSTR bstrVal;
VarBstrFromDate(GETVALUE(var, date), 0, 0, &bstrVal);
BSTR2NPVar(bstrVal, npvar, instance);
break;
default:
if (var->vt & VT_ARRAY) {
obj = SafeArray2NPObject(GETVALUE(var, parray), 0, NULL, instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
break;
}
}
#undef GETVALUE
void
NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance)
{
USES_CONVERSION;
if (!var || !npvar) {
return;
}
switch (npvar->type) {
case NPVariantType_Void:
var->vt = VT_VOID;
var->ulVal = 0;
break;
case NPVariantType_Null:
var->vt = VT_PTR;
var->byref = NULL;
break;
case NPVariantType_Bool:
var->vt = VT_BOOL;
var->ulVal = npvar->value.boolValue;
break;
case NPVariantType_Int32:
var->vt = VT_UI4;
var->ulVal = npvar->value.intValue;
break;
case NPVariantType_Double:
var->vt = VT_R8;
var->dblVal = npvar->value.doubleValue;
break;
case NPVariantType_String:
var->vt = VT_BSTR;
var->bstrVal = Utf8StringToBstr(npvar->value.stringValue.UTF8Characters, npvar->value.stringValue.UTF8Length);
break;
case NPVariantType_Object:
NPIdentifier *identifiers = NULL;
uint32_t identifierCount = 0;
NPObject *object = NPVARIANT_TO_OBJECT(*npvar);
if (NPNFuncs.enumerate(instance, object, &identifiers, &identifierCount)) {
CComSafeArray<VARIANT> variants;
for (uint32_t index = 0; index < identifierCount; ++index) {
NPVariant npVariant;
if (NPNFuncs.getproperty(instance, object, identifiers[index], &npVariant)) {
if (npVariant.type != NPVariantType_Object) {
CComVariant variant;
NPVar2Variant(&npVariant, &variant, instance);
variants.Add(variant);
}
NPNFuncs.releasevariantvalue(&npVariant);
}
}
NPNFuncs.memfree(identifiers);
*reinterpret_cast<CComVariant*>(var) = variants;
}
else {
var->vt = VT_VOID;
var->ulVal = 0;
}
break;
}
}
| 007slmg-ff | ff-activex-host/ffactivex/variants.cpp | C++ | lgpl | 10,569 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <algorithm>
#include <string>
#include "GenericNPObject.h"
static NPObject*
AllocateGenericNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, false);
}
static NPObject*
AllocateMethodNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, true);
}
static void
DeallocateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
GenericNPObject *m = (GenericNPObject *)obj;
delete m;
}
static void
InvalidateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
((GenericNPObject *)obj)->Invalidate();
}
NPClass GenericNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateGenericNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
NPClass MethodNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateMethodNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
// Some standard JavaScript methods
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) {
GenericNPObject *map = (GenericNPObject *)object;
if (!map || map->invalid) return false;
// no args expected or cared for...
std::string out;
std::vector<NPVariant>::iterator it;
for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) {
if (NPVARIANT_IS_VOID(*it)) {
out += ",";
}
else if (NPVARIANT_IS_NULL(*it)) {
out += ",";
}
else if (NPVARIANT_IS_BOOLEAN(*it)) {
if ((*it).value.boolValue) {
out += "true,";
}
else {
out += "false,";
}
}
else if (NPVARIANT_IS_INT32(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%d,", (*it).value.intValue);
out += tmp;
}
else if (NPVARIANT_IS_DOUBLE(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%f,", (*it).value.doubleValue);
out += tmp;
}
else if (NPVARIANT_IS_STRING(*it)) {
out += (*it).value.stringValue.UTF8Characters;
out += ",";
}
else if (NPVARIANT_IS_OBJECT(*it)) {
out += "[object],";
}
}
// calculate how much space we need
std::string::size_type size = out.length();
char *s = (char *)NPNFuncs.memalloc(size * sizeof(char));
if (NULL == s) {
return false;
}
memcpy(s, out.c_str(), size);
s[size - 1] = 0; // overwrite the last ","
STRINGZ_TO_NPVARIANT(s, (*result));
return true;
}
// Some helpers
static void free_numeric_element(NPVariant elem) {
NPNFuncs.releasevariantvalue(&elem);
}
static void free_alpha_element(std::pair<const char *, NPVariant> elem) {
NPNFuncs.releasevariantvalue(&(elem.second));
}
// And now the GenericNPObject implementation
GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj):
invalid(false), defInvoker(NULL), defInvokerObject(NULL) {
NPVariant val;
INT32_TO_NPVARIANT(0, val);
immutables["length"] = val;
if (!isMethodObj) {
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &MethodNPObjectClass);
if (NULL == obj) {
throw NULL;
}
((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this);
OBJECT_TO_NPVARIANT(obj, val);
immutables["toString"] = val;
}
}
GenericNPObject::~GenericNPObject() {
for_each(immutables.begin(), immutables.end(), free_alpha_element);
for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element);
for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element);
}
bool GenericNPObject::HasMethod(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL != immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
}
return false;
}
bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(immutables[key])
&& immutables[key].value.objectValue->_class->invokeDefault) {
return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result);
}
}
else if (alpha_mapper.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(alpha_mapper[key])
&& alpha_mapper[key].value.objectValue->_class->invokeDefault) {
return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result);
}
}
}
return true;
}
bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (defInvoker) {
defInvoker(defInvokerObject, args, argCount, result);
}
return true;
}
// This method is also called before the JS engine attempts to add a new
// property, most likely it's trying to check that the key is supported.
// It only returns false if the string name was not found, or does not
// hold a callable object
bool GenericNPObject::HasProperty(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL == immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
return false;
}
return true;
}
static bool CopyNPVariant(NPVariant *dst, const NPVariant *src)
{
dst->type = src->type;
if (NPVARIANT_IS_STRING(*src)) {
NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8));
if (NULL == str) {
return false;
}
dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length;
memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length);
str[dst->value.stringValue.UTF8Length] = 0;
dst->value.stringValue.UTF8Characters = str;
}
else if (NPVARIANT_IS_OBJECT(*src)) {
NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src));
dst->value.objectValue = src->value.objectValue;
}
else {
dst->value = src->value;
}
return true;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (!CopyNPVariant(result, &(immutables[key]))) {
return false;
}
}
else if (alpha_mapper.count(key) > 0) {
if (!CopyNPVariant(result, &(alpha_mapper[key]))) {
return false;
}
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
if (!CopyNPVariant(result, &(numeric_mapper[key]))) {
return false;
}
}
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
// the key is already defined as immutable, check the new value type
if (value->type != immutables[key].type) {
return false;
}
// Seems ok, copy the new value
if (!CopyNPVariant(&(immutables[key]), value)) {
return false;
}
}
else if (!CopyNPVariant(&(alpha_mapper[key]), value)) {
return false;
}
}
else {
// assume int...
NPVariant var;
if (!CopyNPVariant(&var, value)) {
return false;
}
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (key >= numeric_mapper.size()) {
// there's a gap we need to fill
NPVariant pad;
VOID_TO_NPVARIANT(pad);
numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad);
}
numeric_mapper.at(key) = var;
NPVARIANT_TO_INT32(immutables["length"])++;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::RemoveProperty(NPIdentifier name) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (alpha_mapper.count(key) > 0) {
NPNFuncs.releasevariantvalue(&(alpha_mapper[key]));
alpha_mapper.erase(key);
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
NPNFuncs.releasevariantvalue(&(numeric_mapper[key]));
numeric_mapper.erase(numeric_mapper.begin() + key);
}
NPVARIANT_TO_INT32(immutables["length"])--;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) {
if (invalid) return false;
try {
*identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size());
if (NULL == *identifiers) {
return false;
}
*identifierCount = 0;
std::vector<NPVariant>::iterator it;
unsigned int i = 0;
char str[10] = "";
for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) {
// skip empty (padding) elements
if (NPVARIANT_IS_VOID(*it)) continue;
_snprintf(str, sizeof(str), "%u", i);
(*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str);
}
}
catch (...) {
}
return true;
}
| 007slmg-ff | ff-activex-host/ffactivex/GenericNPObject.cpp | C++ | lgpl | 12,906 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by ffactivex.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 007slmg-ff | ff-activex-host/ffactivex/resource.h | C | lgpl | 403 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
class CAxHost {
private:
CAxHost(const CAxHost &);
NPP instance;
bool isValidClsID;
bool isKnown;
protected:
// The window handle to our plugin area in the browser
HWND Window;
WNDPROC OldProc;
// The class/prog id of the control
CLSID ClsID;
LPCWSTR CodeBaseUrl;
CControlEventSinkInstance *Sink;
public:
CAxHost(NPP inst);
~CAxHost();
CControlSiteInstance *Site;
PropertyList Props;
void setWindow(HWND win);
HWND getWinfow();
void UpdateRect(RECT rcPos);
bool verifyClsID(LPOLESTR oleClsID);
bool setClsID(const char *clsid);
bool setClsIDFromProgID(const char *progid);
void setCodeBaseUrl(LPCWSTR clsid);
bool hasValidClsID();
bool CreateControl(bool subscribeToEvents);
bool AddEventHandler(wchar_t *name, wchar_t *handler);
int16 HandleEvent(void *event);
NPObject *GetScriptableObject();
};
| 007slmg-ff | ff-activex-host/ffactivex/axhost.h | C++ | lgpl | 2,570 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// ffactivex.cpp : Defines the exported functions for the DLL application.
//
#include "ffactivex.h"
#include "common/stdafx.h"
#include "axhost.h"
#include "atlutil.h"
#include "authorize.h"
// A list of trusted domains
// Each domain name may start with a '*' to specify that sub domains are
// trusted as well
// Note that a '.' is not enforced after the '*'
static const char *TrustedLocations[] = {NULL};
static const unsigned int numTrustedLocations = 0;
static const char *LocalhostName = "localhost";
static const bool TrustLocalhost = true;
void *
ffax_calloc(unsigned int size)
{
void *ptr = NULL;
ptr = NPNFuncs.memalloc(size);
if (ptr) {
memset(ptr, 0, size);
}
return ptr;
}
void
ffax_free(void *ptr)
{
if (ptr)
NPNFuncs.memfree(ptr);
}
//
// Gecko API
//
static unsigned int log_level = 0;
static char *logger = NULL;
void
log(NPP instance, unsigned int level, char *message, ...)
{
NPVariant result;
NPVariant args;
NPObject *globalObj = NULL;
bool rc = false;
char *formatted = NULL;
char *new_formatted = NULL;
int buff_len = 0;
int size = 0;
va_list list;
if (!logger || (level > log_level)) {
return;
}
buff_len = strlen(message);
buff_len += buff_len / 10;
formatted = (char *)calloc(1, buff_len);
while (true) {
va_start(list, message);
size = vsnprintf_s(formatted, buff_len, _TRUNCATE, message, list);
va_end(list);
if (size > -1 && size < buff_len)
break;
buff_len *= 2;
new_formatted = (char *)realloc(formatted, buff_len);
if (NULL == new_formatted) {
free(formatted);
return;
}
formatted = new_formatted;
new_formatted = NULL;
}
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
NPIdentifier handler = NPNFuncs.getstringidentifier(logger);
STRINGZ_TO_NPVARIANT(formatted, args);
bool success = NPNFuncs.invoke(instance, globalObj, handler, &args, 1, &result);
NPNFuncs.releasevariantvalue(&result);
NPNFuncs.releaseobject(globalObj);
free(formatted);
}
static bool
MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl)
{
USES_CONVERSION;
bool rc = false;
CUrl url;
if (!numTrustedLocations) {
return true;
}
rc = url.CrackUrl(matchUrl, ATL_URL_DECODE);
if (!rc) {
log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL");
return false;
}
if ( (url.GetScheme() == ATL_URL_SCHEME_FILE)
|| (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){
return TrustLocalhost;
}
for (unsigned int i = 0; i < numTrustedLocations; ++i) {
if (TrustedLocations[i][0] == '*') {
// sub domains are trusted
unsigned int len = strlen(TrustedLocations[i]);
bool match = 0;
if (url.GetHostNameLength() < len) {
// can't be a match
continue;
}
--len; // skip the '*'
match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name
TrustedLocations[i] + 1, // skip the '*'
len) == 0 ? true : false;
if (match) {
return true;
}
}
else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) {
return true;
}
}
return false;
}
static bool
VerifySiteLock(NPP instance)
{
USES_CONVERSION;
NPObject *globalObj = NULL;
NPIdentifier identifier;
NPVariant varLocation;
NPVariant varHref;
bool rc = false;
// Get the window object.
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation);
NPNFuncs.releaseobject(globalObj);
if (!rc){
log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref);
NPNFuncs.releasevariantvalue(&varLocation);
if (!rc) {
log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property");
return false;
}
rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters));
NPNFuncs.releasevariantvalue(&varHref);
if (false == rc) {
log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted");
}
return rc;
}
/*
* Create a new plugin instance, most probably through an embed/object HTML
* element.
*
* Any private data we want to keep for this instance can be saved into
* [instance->pdata].
* [saved] might hold information a previous instance that was invoked from the
* same URL has saved for us.
*/
NPError
NPP_New(NPMIMEType pluginType,
NPP instance, uint16 mode,
int16 argc, char *argn[],
char *argv[], NPSavedData *saved)
{
NPError rc = NPERR_NO_ERROR;
NPObject *browser = NULL;
CAxHost *host = NULL;
PropertyList events;
int16 i = 0;
USES_CONVERSION;
//_asm {int 3};
if (!instance || (0 == NPNFuncs.size)) {
return NPERR_INVALID_PARAM;
}
#ifdef NO_REGISTRY_AUTHORIZE
// Verify that we're running from a trusted location
if (!VerifySiteLock(instance)) {
return NPERR_GENERIC_ERROR;
}
#endif
instance->pdata = NULL;
#ifndef NO_REGISTRY_AUTHORIZE
if (!TestAuthorization (instance,
argc,
argn,
argv,
pluginType)) {
return NPERR_GENERIC_ERROR;
}
#endif
// TODO: Check the pluginType to make sure we're being called with the rigth MIME Type
do {
// Create a plugin instance, the actual control will be created once we
// are given a window handle
host = new CAxHost(instance);
if (!host) {
rc = NPERR_OUT_OF_MEMORY_ERROR;
log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host");
break;
}
// Iterate over the arguments we've been passed
for (i = 0;
(i < argc) && (NPERR_NO_ERROR == rc);
++i) {
// search for any needed information: clsid, event handling directives, etc.
if (0 == strnicmp(argn[i], PARAM_CLSID, strlen(PARAM_CLSID))) {
// The class id of the control we are asked to load
host->setClsID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_PROGID, strlen(PARAM_PROGID))) {
// The class id of the control we are asked to load
host->setClsIDFromProgID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_DEBUG, strlen(PARAM_DEBUG))) {
// Logging verbosity
log_level = atoi(argv[i]);
log(instance, 0, "AxHost.NPP_New: debug level set to %d", log_level);
}
else if (0 == strnicmp(argn[i], PARAM_LOGGER, strlen(PARAM_LOGGER))) {
// Logger function
logger = strdup(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_ONEVENT, strlen(PARAM_ONEVENT))) {
// A request to handle one of the activex's events in JS
events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i])));
}
else if (0 == strnicmp(argn[i], PARAM_PARAM, strlen(PARAM_PARAM))) {
CComBSTR paramName = argn[i] + strlen(PARAM_PARAM);
CComBSTR paramValue(Utf8StringToBstr(argv[i], strlen(argv[i])));
// Check for existing params with the same name
BOOL bFound = FALSE;
for (unsigned long j = 0; j < host->Props.GetSize(); j++) {
if (wcscmp(host->Props.GetNameOf(j), (BSTR) paramName) == 0) {
bFound = TRUE;
break;
}
}
// If the parameter already exists, don't add it to the
// list again.
if (bFound) {
continue;
}
// Add named parameter to list
CComVariant v(paramValue);
host->Props.AddNamedProperty(paramName, v);
}
else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) {
if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) {
host->setCodeBaseUrl(A2W(argv[i]));
}
else {
log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location");
}
}
}
if (NPERR_NO_ERROR != rc)
break;
// Make sure we have all the information we need to initialize a new instance
if (!host->hasValidClsID()) {
rc = NPERR_INVALID_PARAM;
log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID");
break;
}
instance->pdata = host;
// if no events were requested, don't fail if subscribing fails
if (!host->CreateControl(events.GetSize() ? true : false)) {
rc = NPERR_GENERIC_ERROR;
log(instance, 0, "AxHost.NPP_New: failed to create the control");
break;
}
for (unsigned int j = 0; j < events.GetSize(); j++) {
if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) {
//rc = NPERR_GENERIC_ERROR;
//break;
}
}
if (NPERR_NO_ERROR != rc)
break;
} while (0);
if (NPERR_NO_ERROR != rc) {
delete host;
}
return rc;
}
/*
* Destroy an existing plugin instance.
*
* [save] can be used to save information for a future instance of our plugin
* that'll be invoked by the same URL.
*/
NPError
NPP_Destroy(NPP instance, NPSavedData **save)
{
// _asm {int 3};
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
log(instance, 0, "NPP_Destroy: destroying the control...");
CAxHost *host = (CAxHost *)instance->pdata;
delete host;
instance->pdata = NULL;
return NPERR_NO_ERROR;
}
/*
* Sets an instance's window parameters.
*/
NPError
NPP_SetWindow(NPP instance, NPWindow *window)
{
CAxHost *host = NULL;
RECT rcPos;
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
host = (CAxHost *)instance->pdata;
host->setWindow((HWND)window->window);
rcPos.left = 0;
rcPos.top = 0;
rcPos.right = window->width;
rcPos.bottom = window->height;
host->UpdateRect(rcPos);
return NPERR_NO_ERROR;
}
| 007slmg-ff | ff-activex-host/ffactivex/ffactivex.cpp | C++ | lgpl | 12,205 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "PropertyBag.h"
CPropertyBag::CPropertyBag()
{
}
CPropertyBag::~CPropertyBag()
{
}
///////////////////////////////////////////////////////////////////////////////
// IPropertyBag implementation
HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
VARTYPE vt = pVar->vt;
VariantInit(pVar);
for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++)
{
if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0)
{
const VARIANT *pvSrc = m_PropertyList.GetValueOf(i);
if (!pvSrc)
{
return E_FAIL;
}
CComVariant vNew;
HRESULT hr = (vt == VT_EMPTY) ?
vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc);
if (FAILED(hr))
{
return E_FAIL;
}
// Copy the new value
vNew.Detach(pVar);
return S_OK;
}
}
// Property does not exist in the bag
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
CComBSTR bstrName(pszPropName);
m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar);
return S_OK;
}
| 007slmg-ff | ff-activex-host/ffactivex/common/PropertyBag.cpp | C++ | lgpl | 3,426 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYBAG_H
#define PROPERTYBAG_H
#include "PropertyList.h"
// Object wrapper for property list. This class can be set up with a
// list of properties and used to initialise a control with them
class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>,
public IPropertyBag
{
// List of properties in the bag
PropertyList m_PropertyList;
public:
// Constructor
CPropertyBag();
// Destructor
virtual ~CPropertyBag();
BEGIN_COM_MAP(CPropertyBag)
COM_INTERFACE_ENTRY(IPropertyBag)
END_COM_MAP()
// IPropertyBag methods
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog);
virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar);
};
typedef CComObject<CPropertyBag> CPropertyBagInstance;
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/PropertyBag.h | C++ | lgpl | 2,769 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITE_H
#define CONTROLSITE_H
#include "IOleCommandTargetImpl.h"
#include "PropertyList.h"
// If you created a class derived from CControlSite, use the following macro
// in the interface map of the derived class to include all the necessary
// interfaces.
#define CCONTROLSITE_INTERFACES() \
COM_INTERFACE_ENTRY(IOleWindow) \
COM_INTERFACE_ENTRY(IOleClientSite) \
COM_INTERFACE_ENTRY(IOleInPlaceSite) \
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) \
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) \
COM_INTERFACE_ENTRY(IOleControlSite) \
COM_INTERFACE_ENTRY(IDispatch) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) \
COM_INTERFACE_ENTRY(IOleCommandTarget) \
COM_INTERFACE_ENTRY(IServiceProvider) \
COM_INTERFACE_ENTRY(IBindStatusCallback) \
COM_INTERFACE_ENTRY(IWindowForBindingUI)
// Temoporarily removed by bug 200680. Stops controls misbehaving and calling
// windowless methods when they shouldn't.
// COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \
// Class that defines the control's security policy with regards to
// what controls it hosts etc.
class CControlSiteSecurityPolicy
{
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0;
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0;
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0;
};
//
// Class for hosting an ActiveX control
//
// This class supports both windowed and windowless classes. The normal
// steps to hosting a control are this:
//
// CControlSiteInstance *pSite = NULL;
// CControlSiteInstance::CreateInstance(&pSite);
// pSite->AddRef();
// pSite->Create(clsidControlToCreate);
// pSite->Attach(hwndParentWindow, rcPosition);
//
// Where propertyList is a named list of values to initialise the new object
// with, hwndParentWindow is the window in which the control is being created,
// and rcPosition is the position in window coordinates where the control will
// be rendered.
//
// Destruction is this:
//
// pSite->Detach();
// pSite->Release();
// pSite = NULL;
class CControlSite : public CComObjectRootEx<CComSingleThreadModel>,
public CControlSiteSecurityPolicy,
public IOleClientSite,
public IOleInPlaceSiteWindowless,
public IOleControlSite,
public IAdviseSinkEx,
public IDispatch,
public IServiceProvider,
public IOleCommandTargetImpl<CControlSite>,
public IBindStatusCallback,
public IWindowForBindingUI
{
public:
// Site management values
// Handle to parent window
HWND m_hWndParent;
// Position of the site and the contained object
RECT m_rcObjectPos;
// Flag indicating if client site should be set early or late
unsigned m_bSetClientSiteFirst:1;
// Flag indicating whether control is visible or not
unsigned m_bVisibleAtRuntime:1;
// Flag indicating if control is in-place active
unsigned m_bInPlaceActive:1;
// Flag indicating if control is UI active
unsigned m_bUIActive:1;
// Flag indicating if control is in-place locked and cannot be deactivated
unsigned m_bInPlaceLocked:1;
// Flag indicating if the site allows windowless controls
unsigned m_bSupportWindowlessActivation:1;
// Flag indicating if control is windowless (after being created)
unsigned m_bWindowless:1;
// Flag indicating if only safely scriptable controls are allowed
unsigned m_bSafeForScriptingObjectsOnly:1;
// Pointer to an externally registered service provider
CComPtr<IServiceProvider> m_spServiceProvider;
// Pointer to the OLE container
CComPtr<IOleContainer> m_spContainer;
// Return the default security policy object
static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy();
protected:
// Pointers to object interfaces
// Raw pointer to the object
CComPtr<IUnknown> m_spObject;
// Pointer to objects IViewObject interface
CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject;
// Pointer to object's IOleObject interface
CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject;
// Pointer to object's IOleInPlaceObject interface
CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject;
// Pointer to object's IOleInPlaceObjectWindowless interface
CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless;
// CLSID of the control
CLSID m_CLSID;
// Parameter list
PropertyList m_ParameterList;
// Pointer to the security policy
CControlSiteSecurityPolicy *m_pSecurityPolicy;
// Binding variables
// Flag indicating whether binding is in progress
unsigned m_bBindingInProgress;
// Result from the binding operation
HRESULT m_hrBindResult;
// Double buffer drawing variables used for windowless controls
// Area of buffer
RECT m_rcBuffer;
// Bitmap to buffer
HBITMAP m_hBMBuffer;
// Bitmap to buffer
HBITMAP m_hBMBufferOld;
// Device context
HDC m_hDCBuffer;
// Clipping area of site
HRGN m_hRgnBuffer;
// Flags indicating how the buffer was painted
DWORD m_dwBufferFlags;
// Ambient properties
// Locale ID
LCID m_nAmbientLocale;
// Foreground colour
COLORREF m_clrAmbientForeColor;
// Background colour
COLORREF m_clrAmbientBackColor;
// Flag indicating if control should hatch itself
bool m_bAmbientShowHatching:1;
// Flag indicating if control should have grab handles
bool m_bAmbientShowGrabHandles:1;
// Flag indicating if control is in edit/user mode
bool m_bAmbientUserMode:1;
// Flag indicating if control has a 3d border or not
bool m_bAmbientAppearance:1;
protected:
// Notifies the attached control of a change to an ambient property
virtual void FireAmbientPropertyChange(DISPID id);
public:
// Construction and destruction
// Constructor
CControlSite();
// Destructor
virtual ~CControlSite();
BEGIN_COM_MAP(CControlSite)
CCONTROLSITE_INTERFACES()
END_COM_MAP()
BEGIN_OLECOMMAND_TABLE()
END_OLECOMMAND_TABLE()
// Returns the window used when processing ole commands
HWND GetCommandTargetWindow()
{
return NULL; // TODO
}
// Object creation and management functions
// Creates and initialises an object
virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(),
LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL);
// Attaches the object to the site
virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL);
// Detaches the object from the site
virtual HRESULT Detach();
// Returns the IUnknown pointer for the object
virtual HRESULT GetControlUnknown(IUnknown **ppObject);
// Sets the bounding rectangle for the object
virtual HRESULT SetPosition(const RECT &rcPos);
// Draws the object using the provided DC
virtual HRESULT Draw(HDC hdc);
// Performs the specified action on the object
virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL);
// Sets an advise sink up for changes to the object
virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie);
// Removes an advise sink
virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie);
// Register an external service provider object
virtual void SetServiceProvider(IServiceProvider *pSP)
{
m_spServiceProvider = pSP;
}
virtual void SetContainer(IOleContainer *pContainer)
{
m_spContainer = pContainer;
}
// Set the security policy object. Ownership of this object remains with the caller and the security
// policy object is meant to exist for as long as it is set here.
virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy)
{
m_pSecurityPolicy = pSecurityPolicy;
}
virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const
{
return m_pSecurityPolicy;
}
// Methods to set ambient properties
virtual void SetAmbientUserMode(BOOL bUser);
// Inline helper methods
// Returns the object's CLSID
virtual const CLSID &GetObjectCLSID() const
{
return m_CLSID;
}
// Tests if the object is valid or not
virtual BOOL IsObjectValid() const
{
return (m_spObject) ? TRUE : FALSE;
}
// Returns the parent window to this one
virtual HWND GetParentWindow() const
{
return m_hWndParent;
}
// Returns the inplace active state of the object
virtual BOOL IsInPlaceActive() const
{
return m_bInPlaceActive;
}
// CControlSiteSecurityPolicy
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(const IID &iid);
// IServiceProvider
virtual HRESULT STDMETHODCALLTYPE QueryService(REFGUID guidService, REFIID riid, void** ppv);
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
// IAdviseSink implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed);
virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex);
virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk);
virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void);
virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void);
// IAdviseSink2
virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk);
// IAdviseSinkEx implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus);
// IOleWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleClientSite implementation
virtual HRESULT STDMETHODCALLTYPE SaveObject(void);
virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk);
virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer);
virtual HRESULT STDMETHODCALLTYPE ShowObject(void);
virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow);
virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void);
// IOleInPlaceSite implementation
virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo);
virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant);
virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void);
virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void);
virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void);
virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect);
// IOleInPlaceSiteEx implementation
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw);
virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void);
// IOleInPlaceSiteWindowless implementation
virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetCapture(void);
virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture);
virtual HRESULT STDMETHODCALLTYPE GetFocus(void);
virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus);
virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC);
virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC);
virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip);
virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc);
virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult);
// IOleControlSite implementation
virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void);
virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock);
virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp);
virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers);
virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus);
virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void);
// IBindStatusCallback
virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib);
virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority);
virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved);
virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText);
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed);
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk);
// IWindowForBindingUI
virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd);
};
typedef CComObject<CControlSite> CControlSiteInstance;
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/ControlSite.h | C++ | lgpl | 18,659 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "ItemContainer.h"
CItemContainer::CItemContainer()
{
}
CItemContainer::~CItemContainer()
{
}
///////////////////////////////////////////////////////////////////////////////
// IParseDisplayName implementation
HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut)
{
// TODO
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum)
{
HRESULT hr = E_NOTIMPL;
/*
if (ppenum == NULL)
{
return E_POINTER;
}
*ppenum = NULL;
typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk;
enumunk* p = NULL;
p = new enumunk;
if(p == NULL)
{
return E_OUTOFMEMORY;
}
hr = p->Init();
if (SUCCEEDED(hr))
{
hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum);
}
if (FAILED(hRes))
{
delete p;
}
*/
return hr;
}
HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock)
{
// TODO
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleItemContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject)
{
if (pszItem == NULL)
{
return E_INVALIDARG;
}
if (ppvObject == NULL)
{
return E_INVALIDARG;
}
*ppvObject = NULL;
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage)
{
// TODO
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem)
{
// TODO
return MK_E_NOOBJECT;
}
| 007slmg-ff | ff-activex-host/ffactivex/common/ItemContainer.cpp | C++ | lgpl | 4,191 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLEVENTSINK_H
#define CONTROLEVENTSINK_H
#include <map>
// This class listens for events from the specified control
class CControlEventSink :
public CComObjectRootEx<CComSingleThreadModel>,
public IDispatch
{
public:
CControlEventSink();
// Current event connection point
CComPtr<IConnectionPoint> m_spEventCP;
CComPtr<ITypeInfo> m_spEventSinkTypeInfo;
DWORD m_dwEventCookie;
IID m_EventIID;
typedef std::map<DISPID, wchar_t *> EventMap;
EventMap events;
NPP instance;
protected:
virtual ~CControlEventSink();
bool m_bSubscribed;
static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw)
{
CControlEventSink *pThis = (CControlEventSink *) pv;
if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) &&
IsEqualIID(pThis->m_EventIID, riid))
{
return pThis->QueryInterface(__uuidof(IDispatch), ppv);
}
return E_NOINTERFACE;
}
public:
BEGIN_COM_MAP(CControlEventSink)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI)
END_COM_MAP()
virtual HRESULT SubscribeToEvents(IUnknown *pControl);
virtual void UnsubscribeFromEvents();
virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo);
virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
};
typedef CComObject<CControlEventSink> CControlEventSinkInstance;
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/ControlEventSink.h | C++ | lgpl | 4,193 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "stdafx.h"
#include "ControlSiteIPFrame.h"
CControlSiteIPFrame::CControlSiteIPFrame()
{
m_hwndFrame = NULL;
}
CControlSiteIPFrame::~CControlSiteIPFrame()
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
if (phwnd == NULL)
{
return E_INVALIDARG;
}
*phwnd = m_hwndFrame;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceUIWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceFrame implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID)
{
return E_NOTIMPL;
}
| 007slmg-ff | ff-activex-host/ffactivex/common/ControlSiteIPFrame.cpp | C++ | lgpl | 4,105 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_)
#define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// under MSVC shut off copious warnings about debug symbol too long
#ifdef _MSC_VER
#pragma warning( disable: 4786 )
#endif
//#include "jstypes.h"
//#include "prtypes.h"
// Mozilla headers
//#include "jscompat.h"
//#include "prthread.h"
//#include "prprf.h"
//#include "nsID.h"
//#include "nsIComponentManager.h"
//#include "nsIServiceManager.h"
//#include "nsStringAPI.h"
//#include "nsCOMPtr.h"
//#include "nsComponentManagerUtils.h"
//#include "nsServiceManagerUtils.h"
//#include "nsIDocument.h"
//#include "nsIDocumentObserver.h"
//#include "nsVoidArray.h"
//#include "nsIDOMNode.h"
//#include "nsIDOMNodeList.h"
//#include "nsIDOMDocument.h"
//#include "nsIDOMDocumentType.h"
//#include "nsIDOMElement.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_APARTMENT_THREADED
//#define _ATL_STATIC_REGISTRY
// #define _ATL_DEBUG_INTERFACES
// ATL headers
// The ATL headers that come with the platform SDK have bad for scoping
#if _MSC_VER >= 1400
#pragma conform(forScope, push, atlhack, off)
#endif
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
#include <atlctl.h>
#if _MSC_VER >= 1400
#pragma conform(forScope, pop, atlhack)
#endif
#include <mshtml.h>
#include <mshtmhst.h>
#include <docobj.h>
//#include <winsock2.h>
#include <comdef.h>
#include <vector>
#include <list>
#include <string>
// New winsock2.h doesn't define this anymore
typedef long int32;
#define NS_SCRIPTABLE
#include "nscore.h"
#include "npapi.h"
//#include "npupp.h"
#include "npfunctions.h"
#include "nsID.h"
#include <npruntime.h>
#include "../variants.h"
#include "PropertyList.h"
#include "PropertyBag.h"
#include "ItemContainer.h"
#include "ControlSite.h"
#include "ControlSiteIPFrame.h"
#include "ControlEventSink.h"
extern NPNetscapeFuncs NPNFuncs;
// Turn off warnings about debug symbols for templates being too long
#pragma warning(disable : 4786)
#define TRACE_METHOD(fn) \
{ \
ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \
}
#define TRACE_METHOD_ARGS(fn, pattern, args) \
{ \
ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \
}
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#define NS_ASSERTION(x, y)
#endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
| 007slmg-ff | ff-activex-host/ffactivex/common/StdAfx.h | C++ | lgpl | 5,055 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "ControlEventSink.h"
CControlEventSink::CControlEventSink() :
m_dwEventCookie(0),
m_bSubscribed(false),
m_EventIID(GUID_NULL),
events()
{
}
CControlEventSink::~CControlEventSink()
{
UnsubscribeFromEvents();
}
BOOL
CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo)
{
iid = GUID_NULL;
if (!pControl)
{
return E_INVALIDARG;
}
// IProvideClassInfo2 way is easiest
// CComQIPtr<IProvideClassInfo2> classInfo2 = pControl;
// if (classInfo2)
// {
// classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid);
// if (!::IsEqualIID(iid, GUID_NULL))
// {
// return TRUE;
// }
// }
// Yuck, the hard way
CComQIPtr<IProvideClassInfo> classInfo = pControl;
if (!classInfo)
{
return FALSE;
}
// Search the class type information for the default source interface
// which is the outgoing event sink.
CComPtr<ITypeInfo> classTypeInfo;
classInfo->GetClassInfo(&classTypeInfo);
if (!classTypeInfo)
{
return FALSE;
}
TYPEATTR *classAttr = NULL;
if (FAILED(classTypeInfo->GetTypeAttr(&classAttr)))
{
return FALSE;
}
INT implFlags = 0;
for (UINT i = 0; i < classAttr->cImplTypes; i++)
{
// Search for the interface with the [default, source] attr
if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) &&
implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE))
{
CComPtr<ITypeInfo> eventSinkTypeInfo;
HREFTYPE hRefType;
if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) &&
SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo)))
{
TYPEATTR *eventSinkAttr = NULL;
if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr)))
{
iid = eventSinkAttr->guid;
if (typeInfo)
{
*typeInfo = eventSinkTypeInfo.p;
(*typeInfo)->AddRef();
}
eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr);
}
}
break;
}
}
classTypeInfo->ReleaseTypeAttr(classAttr);
return (!::IsEqualIID(iid, GUID_NULL));
}
void CControlEventSink::UnsubscribeFromEvents()
{
if (m_bSubscribed)
{
DWORD tmpCookie = m_dwEventCookie;
m_dwEventCookie = 0;
m_bSubscribed = false;
// Unsubscribe and reset - This seems to complete release and destroy us...
m_spEventCP->Unadvise(tmpCookie);
// Unadvise handles the Release
//m_spEventCP.Release();
}
}
HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl)
{
if (!pControl)
{
return E_INVALIDARG;
}
// Throw away any existing connections
UnsubscribeFromEvents();
// Grab the outgoing event sink IID which will be used to subscribe
// to events via the connection point container.
IID iidEventSink;
CComPtr<ITypeInfo> typeInfo;
if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo))
{
return E_FAIL;
}
// Get the connection point
CComQIPtr<IConnectionPointContainer> ccp = pControl;
CComPtr<IConnectionPoint> cp;
if (!ccp)
{
return E_FAIL;
}
// Custom IID
m_EventIID = iidEventSink;
DWORD dwCookie = 0;
if (!ccp ||
FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)) ||
FAILED(cp->Advise(this, &dwCookie)))
{
return E_FAIL;
}
m_bSubscribed = true;
m_spEventCP = cp;
m_dwEventCookie = dwCookie;
m_spEventSinkTypeInfo = typeInfo;
return S_OK;
}
HRESULT
CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
USES_CONVERSION;
if (DISPATCH_METHOD != wFlags) {
// any other reason to call us?!
return S_FALSE;
}
EventMap::iterator cur = events.find(dispIdMember);
if (events.end() != cur) {
// invoke this event handler
NPVariant result;
NPVariant *args = NULL;
if (pDispParams->cArgs > 0) {
args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant));
if (!args) {
return S_FALSE;
}
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments in reverse order
Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance);
}
}
NPObject *globalObj = NULL;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second));
bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result);
NPNFuncs.releaseobject(globalObj);
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments
if (args[i].type == NPVariantType_String) {
// was allocated earlier by Variant2NPVar
NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters);
}
}
if (!success) {
return S_FALSE;
}
if (pVarResult) {
// set the result
NPVar2Variant(&result, pVarResult, instance);
}
NPNFuncs.releasevariantvalue(&result);
}
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
| 007slmg-ff | ff-activex-host/ffactivex/common/ControlEventSink.cpp | C++ | lgpl | 8,596 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
* Brent Booker
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include <Objsafe.h>
#include "ControlSite.h"
#include "PropertyBag.h"
#include "ControlSiteIPFrame.h"
class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy
{
// Test if the specified class id implements the specified category
BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists);
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
};
BOOL
CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists)
{
bClassExists = FALSE;
// Test if there is a CLSID entry. If there isn't then obviously
// the object doesn't exist and therefore doesn't implement any category.
// In this situation, the function returns REGDB_E_CLASSNOTREG.
CRegKey key;
if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS)
{
// Must fail if we can't even open this!
return FALSE;
}
LPOLESTR szCLSID = NULL;
if (FAILED(StringFromCLSID(clsid, &szCLSID)))
{
return FALSE;
}
USES_CONVERSION;
CRegKey keyCLSID;
LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ);
CoTaskMemFree(szCLSID);
if (lResult != ERROR_SUCCESS)
{
// Class doesn't exist
return FALSE;
}
keyCLSID.Close();
// CLSID exists, so try checking what categories it implements
bClassExists = TRUE;
CComQIPtr<ICatInformation> spCatInfo;
HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo);
if (spCatInfo == NULL)
{
// Must fail if we can't open the category manager
return FALSE;
}
// See what categories the class implements
CComQIPtr<IEnumCATID> spEnumCATID;
if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID)))
{
// Can't enumerate classes in category so fail
return FALSE;
}
// Search for matching categories
BOOL bFound = FALSE;
CATID catidNext = GUID_NULL;
while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK)
{
if (::IsEqualCATID(catid, catidNext))
{
return TRUE;
}
}
return FALSE;
}
// Test if the class is safe to host
BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid)
{
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
// Test the category the object belongs to
return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists);
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (!pObject) {
return FALSE;
}
// Ask the control if its safe for scripting
CComQIPtr<IObjectSafety> spObjectSafety = pObject;
if (!spObjectSafety)
{
return FALSE;
}
DWORD dwSupported = 0; // Supported options (mask)
DWORD dwEnabled = 0; // Enabled options
// Assume scripting via IDispatch
if (FAILED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)))
{
// Interface is not safe or failure.
return FALSE;
}
// Test if safe for scripting
if (!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
// Object says it is not set to be safe, but supports unsafe calling,
// try enabling it and asking again.
if(!(dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) ||
FAILED(spObjectSafety->SetInterfaceSafetyOptions(
iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)) ||
FAILED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)) ||
!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
return FALSE;
}
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Constructor
CControlSite::CControlSite()
{
TRACE_METHOD(CControlSite::CControlSite);
m_hWndParent = NULL;
m_CLSID = CLSID_NULL;
m_bSetClientSiteFirst = FALSE;
m_bVisibleAtRuntime = TRUE;
memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos));
m_bInPlaceActive = FALSE;
m_bUIActive = FALSE;
m_bInPlaceLocked = FALSE;
m_bWindowless = FALSE;
m_bSupportWindowlessActivation = TRUE;
m_bSafeForScriptingObjectsOnly = FALSE;
m_pSecurityPolicy = GetDefaultControlSecurityPolicy();
// Initialise ambient properties
m_nAmbientLocale = 0;
m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT);
m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW);
m_bAmbientUserMode = true;
m_bAmbientShowHatching = true;
m_bAmbientShowGrabHandles = true;
m_bAmbientAppearance = true; // 3d
// Windowless variables
m_hDCBuffer = NULL;
m_hRgnBuffer = NULL;
m_hBMBufferOld = NULL;
m_hBMBuffer = NULL;
}
// Destructor
CControlSite::~CControlSite()
{
TRACE_METHOD(CControlSite::~CControlSite);
Detach();
}
// Create the specified control, optionally providing properties to initialise
// it with and a name.
HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl,
LPCWSTR szCodebase, IBindCtx *pBindContext)
{
TRACE_METHOD(CControlSite::Create);
m_CLSID = clsid;
m_ParameterList = pl;
// See if security policy will allow the control to be hosted
if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid))
{
return E_FAIL;
}
// See if object is script safe
BOOL checkForObjectSafety = FALSE;
if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly)
{
BOOL bClassExists = FALSE;
BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
if (!bClassExists && szCodebase)
{
// Class doesn't exist, so allow code below to fetch it
}
else if (!bIsSafe)
{
// The class is not flagged as safe for scripting, so
// we'll have to create it to ask it if its safe.
checkForObjectSafety = TRUE;
}
}
//Now Check if the control version needs to be updated.
BOOL bUpdateControlVersion = FALSE;
wchar_t *szURL = NULL;
DWORD dwFileVersionMS = 0xffffffff;
DWORD dwFileVersionLS = 0xffffffff;
if(szCodebase)
{
HKEY hk = NULL;
wchar_t wszKey[60] = L"";
wchar_t wszData[MAX_PATH];
LPWSTR pwszClsid = NULL;
DWORD dwSize = 255;
DWORD dwHandle, dwLength, dwRegReturn;
DWORD dwExistingFileVerMS = 0xffffffff;
DWORD dwExistingFileVerLS = 0xffffffff;
BOOL bFoundLocalVerInfo = FALSE;
StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid);
swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32");
if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS )
{
dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize );
RegCloseKey( hk );
}
if(dwRegReturn == ERROR_SUCCESS)
{
VS_FIXEDFILEINFO *pFileInfo;
UINT uLen;
dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle );
LPBYTE lpData = new BYTE[dwLength];
GetFileVersionInfoW(wszData, 0, dwLength, lpData );
bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen );
if(bFoundLocalVerInfo)
{
dwExistingFileVerMS = pFileInfo->dwFileVersionMS;
dwExistingFileVerLS = pFileInfo->dwFileVersionLS;
}
delete [] lpData;
}
// Test if the code base ends in #version=a,b,c,d
const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#'));
if (szHash)
{
if (wcsnicmp(szHash, L"#version=", 9) == 0)
{
int a, b, c, d;
if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4)
{
dwFileVersionMS = MAKELONG(b,a);
dwFileVersionLS = MAKELONG(d,c);
//If local version info was found compare it
if(bFoundLocalVerInfo)
{
if(dwFileVersionMS > dwExistingFileVerMS)
bUpdateControlVersion = TRUE;
if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS))
bUpdateControlVersion = TRUE;
}
}
}
szURL = _wcsdup(szCodebase);
// Terminate at the hash mark
if (szURL)
szURL[szHash - szCodebase] = wchar_t('\0');
}
else
{
szURL = _wcsdup(szCodebase);
}
}
CComPtr<IUnknown> spObject;
HRESULT hr;
//If the control needs to be updated do not call CoCreateInstance otherwise you will lock files
//and force a reboot on CoGetClassObjectFromURL
if(!bUpdateControlVersion)
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)))
{
return E_FAIL;
}
// Drop through, success!
}
}
// Do we need to download the control?
if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion))
{
if (!szURL)
return E_OUTOFMEMORY;
CComPtr<IBindCtx> spBindContext;
CComPtr<IBindStatusCallback> spBindStatusCallback;
CComPtr<IBindStatusCallback> spOldBSC;
// Create our own bind context or use the one provided?
BOOL useInternalBSC = FALSE;
if (!pBindContext)
{
useInternalBSC = TRUE;
hr = CreateBindCtx(0, &spBindContext);
if (FAILED(hr))
{
free(szURL);
return hr;
}
spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this);
hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0);
if (FAILED(hr))
{
free(szURL);
return hr;
}
}
else
{
spBindContext = pBindContext;
}
//If the version from the CODEBASE value is greater than the installed control
//Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt
if(bUpdateControlVersion)
{
hr = CoGetClassObjectFromURL(CLSID_NULL, szCodebase, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext,
CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER,
0, IID_IClassFactory, NULL);
}
else
{
hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown,
NULL);
}
free(szURL);
// Handle the internal binding synchronously so the object exists
// or an error code is available when the method returns.
if (useInternalBSC)
{
if (MK_S_ASYNCHRONOUS == hr)
{
m_bBindingInProgress = TRUE;
m_hrBindResult = E_FAIL;
// Spin around waiting for binding to complete
HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
while (m_bBindingInProgress)
{
MSG msg;
// Process pending messages
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!::GetMessage(&msg, NULL, 0, 0))
{
m_bBindingInProgress = FALSE;
break;
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if (!m_bBindingInProgress)
break;
// Sleep for a bit or the next msg to appear
::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS);
}
::CloseHandle(hFakeEvent);
// Set the result
hr = m_hrBindResult;
}
// Destroy the bind status callback & context
if (spBindStatusCallback)
{
RevokeBindStatusCallback(spBindContext, spBindStatusCallback);
spBindStatusCallback.Release();
spBindContext.Release();
}
}
//added to create control
if (SUCCEEDED(hr))
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)))
{
hr = E_FAIL;
}
}
}
//EOF test code
}
if (spObject)
{
m_spObject = spObject;
}
return hr;
}
// Attach the created control to a window and activate it
HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream)
{
TRACE_METHOD(CControlSite::Attach);
if (hwndParent == NULL)
{
NS_ASSERTION(0, "No parent hwnd");
return E_INVALIDARG;
}
m_hWndParent = hwndParent;
m_rcObjectPos = rcPos;
// Object must have been created
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
m_spIViewObject = m_spObject;
m_spIOleObject = m_spObject;
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
DWORD dwMiscStatus;
m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST)
{
m_bSetClientSiteFirst = TRUE;
}
if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME)
{
m_bVisibleAtRuntime = FALSE;
}
// Some objects like to have the client site as the first thing
// to be initialised (for ambient properties and so forth)
if (m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
// If there is a parameter list for the object and no init stream then
// create one here.
CPropertyBagInstance *pPropertyBag = NULL;
if (pInitStream == NULL && m_ParameterList.GetSize() > 0)
{
CPropertyBagInstance::CreateInstance(&pPropertyBag);
pPropertyBag->AddRef();
for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++)
{
pPropertyBag->Write(m_ParameterList.GetNameOf(i),
const_cast<VARIANT *>(m_ParameterList.GetValueOf(i)));
}
pInitStream = (IPersistPropertyBag *) pPropertyBag;
}
// Initialise the control from store if one is provided
if (pInitStream)
{
CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream;
CComQIPtr<IStream, &IID_IStream> spStream = pInitStream;
CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject;
CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject;
if (spIPersistPropertyBag && spPropertyBag)
{
spIPersistPropertyBag->Load(spPropertyBag, NULL);
}
else if (spIPersistStream && spStream)
{
spIPersistStream->Load(spStream);
}
}
else
{
// Initialise the object if possible
CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject;
if (spIPersistStreamInit)
{
spIPersistStreamInit->InitNew();
}
}
m_spIOleInPlaceObject = m_spObject;
m_spIOleInPlaceObjectWindowless = m_spObject;
if (m_spIOleInPlaceObject)
{
SetPosition(m_rcObjectPos);
}
// In-place activate the object
if (m_bVisibleAtRuntime)
{
DoVerb(OLEIVERB_INPLACEACTIVATE);
}
// For those objects which haven't had their client site set yet,
// it's done here.
if (!m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
return S_OK;
}
// Unhook the control from the window and throw it all away
HRESULT CControlSite::Detach()
{
TRACE_METHOD(CControlSite::Detach);
if (m_spIOleInPlaceObjectWindowless)
{
m_spIOleInPlaceObjectWindowless.Release();
}
if (m_spIOleInPlaceObject)
{
m_spIOleInPlaceObject->InPlaceDeactivate();
m_spIOleInPlaceObject.Release();
}
if (m_spIOleObject)
{
m_spIOleObject->Close(OLECLOSE_NOSAVE);
m_spIOleObject->SetClientSite(NULL);
m_spIOleObject.Release();
}
m_spIViewObject.Release();
m_spObject.Release();
return S_OK;
}
// Return the IUnknown of the contained control
HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject)
{
*ppObject = NULL;
if (m_spObject)
{
m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject);
}
return S_OK;
}
// Subscribe to an event sink on the control
HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
if (pIUnkSink == NULL || pdwCookie == NULL)
{
return E_INVALIDARG;
}
return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie);
}
// Unsubscribe event sink from the control
HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
return AtlUnadvise(m_spObject, iid, dwCookie);
}
// Draw the control
HRESULT CControlSite::Draw(HDC hdc)
{
TRACE_METHOD(CControlSite::Draw);
// Draw only when control is windowless or deactivated
if (m_spIViewObject)
{
if (m_bWindowless || !m_bInPlaceActive)
{
RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos;
m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0);
}
}
else
{
// Draw something to indicate no control is there
HBRUSH hbr = CreateSolidBrush(RGB(200,200,200));
FillRect(hdc, &m_rcObjectPos, hbr);
DeleteObject(hbr);
}
return S_OK;
}
// Execute the specified verb
HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg)
{
TRACE_METHOD(CControlSite::DoVerb);
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos);
}
// Set the position on the control
HRESULT CControlSite::SetPosition(const RECT &rcPos)
{
HWND hwnd;
TRACE_METHOD(CControlSite::SetPosition);
m_rcObjectPos = rcPos;
if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd)))
{
m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos);
}
return S_OK;
}
void CControlSite::FireAmbientPropertyChange(DISPID id)
{
if (m_spObject)
{
CComQIPtr<IOleControl> spControl = m_spObject;
if (spControl)
{
spControl->OnAmbientPropertyChange(id);
}
}
}
void CControlSite::SetAmbientUserMode(BOOL bUserMode)
{
bool bNewMode = bUserMode ? true : false;
if (m_bAmbientUserMode != bNewMode)
{
m_bAmbientUserMode = bNewMode;
FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE);
}
}
///////////////////////////////////////////////////////////////////////////////
// CControlSiteSecurityPolicy implementation
CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy()
{
static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy;
return &defaultControlSecurityPolicy;
}
// Test if the class is safe to host
BOOL CControlSite::IsClassSafeToHost(const CLSID & clsid)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsClassSafeToHost(clsid);
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CControlSite::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
return TRUE;
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CControlSite::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsObjectSafeForScripting(pObject, iid);
return TRUE;
}
BOOL CControlSite::IsObjectSafeForScripting(const IID &iid)
{
return IsObjectSafeForScripting(m_spObject, iid);
}
///////////////////////////////////////////////////////////////////////////////
// IServiceProvider implementation
HRESULT STDMETHODCALLTYPE CControlSite::QueryService(REFGUID guidService, REFIID riid, void** ppv)
{
if (m_spServiceProvider)
return m_spServiceProvider->QueryService(guidService, riid, ppv);
return E_NOINTERFACE;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
if (wFlags & DISPATCH_PROPERTYGET)
{
CComVariant vResult;
switch (dispIdMember)
{
case DISPID_AMBIENT_APPEARANCE:
vResult = CComVariant(m_bAmbientAppearance);
break;
case DISPID_AMBIENT_FORECOLOR:
vResult = CComVariant((long) m_clrAmbientForeColor);
break;
case DISPID_AMBIENT_BACKCOLOR:
vResult = CComVariant((long) m_clrAmbientBackColor);
break;
case DISPID_AMBIENT_LOCALEID:
vResult = CComVariant((long) m_nAmbientLocale);
break;
case DISPID_AMBIENT_USERMODE:
vResult = CComVariant(m_bAmbientUserMode);
break;
case DISPID_AMBIENT_SHOWGRABHANDLES:
vResult = CComVariant(m_bAmbientShowGrabHandles);
break;
case DISPID_AMBIENT_SHOWHATCHING:
vResult = CComVariant(m_bAmbientShowHatching);
break;
default:
return DISP_E_MEMBERNOTFOUND;
}
VariantCopy(pVarResult, &vResult);
return S_OK;
}
return E_FAIL;
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink implementation
void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed)
{
}
void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex)
{
// Redraw the control
InvalidateRect(NULL, FALSE);
}
void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk)
{
}
void STDMETHODCALLTYPE CControlSite::OnSave(void)
{
}
void STDMETHODCALLTYPE CControlSite::OnClose(void)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink2 implementation
void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSinkEx implementation
void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus)
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
*phwnd = m_hWndParent;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleClientSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer)
{
if (!ppContainer) return E_INVALIDARG;
*ppContainer = m_spContainer;
if (*ppContainer)
{
(*ppContainer)->AddRef();
}
return (*ppContainer) ? S_OK : E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void)
{
m_bInPlaceActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void)
{
m_bUIActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
*lprcPosRect = m_rcObjectPos;
*lprcClipRect = m_rcObjectPos;
CControlSiteIPFrameInstance *pIPFrame = NULL;
CControlSiteIPFrameInstance::CreateInstance(&pIPFrame);
pIPFrame->AddRef();
*ppFrame = (IOleInPlaceFrame *) pIPFrame;
*ppDoc = NULL;
lpFrameInfo->fMDIApp = FALSE;
lpFrameInfo->hwndFrame = NULL;
lpFrameInfo->haccel = NULL;
lpFrameInfo->cAccelEntries = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable)
{
m_bUIActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect)
{
if (lprcPosRect == NULL)
{
return E_INVALIDARG;
}
SetPosition(m_rcObjectPos);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteEx implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags)
{
m_bInPlaceActive = TRUE;
if (pfNoRedraw)
{
*pfNoRedraw = FALSE;
}
if (dwFlags & ACTIVATE_WINDOWLESS)
{
if (!m_bSupportWindowlessActivation)
{
return E_INVALIDARG;
}
m_bWindowless = TRUE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void)
{
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteWindowless implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void)
{
// Allow windowless activation?
return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC)
{
if (phDC == NULL)
{
return E_INVALIDARG;
}
// Can't do nested painting
if (m_hDCBuffer != NULL)
{
return E_UNEXPECTED;
}
m_rcBuffer = m_rcObjectPos;
if (pRect != NULL)
{
m_rcBuffer = *pRect;
}
m_hBMBuffer = NULL;
m_dwBufferFlags = grfFlags;
// See if the control wants a DC that is onscreen or offscreen
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
m_hDCBuffer = CreateCompatibleDC(NULL);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy);
m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer);
SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL);
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
}
else
{
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
// Get the window DC
m_hDCBuffer = GetWindowDC(m_hWndParent);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
// Clip the control so it can't trash anywhere it isn't allowed to draw
if (!(m_dwBufferFlags & OLEDC_NODRAW))
{
m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer);
// TODO Clip out opaque areas of sites behind this one
SelectClipRgn(m_hDCBuffer, m_hRgnBuffer);
}
}
*phDC = m_hDCBuffer;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC)
{
// Release the DC
if (hDC == NULL || hDC != m_hDCBuffer)
{
return E_INVALIDARG;
}
// Test if the DC was offscreen or onscreen
if ((m_dwBufferFlags & OLEDC_OFFSCREEN) &&
!(m_dwBufferFlags & OLEDC_NODRAW))
{
// BitBlt the buffer into the control's object
SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL);
HDC hdc = GetWindowDC(m_hWndParent);
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY);
::ReleaseDC(m_hWndParent, hdc);
}
else
{
// TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one
}
// Clean up settings ready for next drawing
if (m_hRgnBuffer)
{
SelectClipRgn(m_hDCBuffer, NULL);
DeleteObject(m_hRgnBuffer);
m_hRgnBuffer = NULL;
}
SelectObject(m_hDCBuffer, m_hBMBufferOld);
if (m_hBMBuffer)
{
DeleteObject(m_hBMBuffer);
m_hBMBuffer = NULL;
}
// Delete the DC
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
::DeleteDC(m_hDCBuffer);
}
else
{
::ReleaseDC(m_hWndParent, m_hDCBuffer);
}
m_hDCBuffer = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase)
{
// Clip the rectangle against the object's size and invalidate it
RECT rcI = { 0, 0, 0, 0 };
if (pRect == NULL)
{
rcI = m_rcObjectPos;
}
else
{
IntersectRect(&rcI, &m_rcObjectPos, pRect);
}
::InvalidateRect(m_hWndParent, &rcI, fErase);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase)
{
if (hRGN == NULL)
{
::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase);
}
else
{
// Clip the region with the object's bounding area
HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos);
if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR)
{
::InvalidateRgn(m_hWndParent, hrgnClip, fErase);
}
DeleteObject(hrgnClip);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc)
{
if (prc == NULL)
{
return E_INVALIDARG;
}
// Clip the rectangle against the object position
RECT rcI = { 0, 0, 0, 0 };
IntersectRect(&rcI, &m_rcObjectPos, prc);
*prc = rcI;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult)
{
if (plResult == NULL)
{
return E_INVALIDARG;
}
// Pass the message to the windowless control
if (m_bWindowless && m_spIOleInPlaceObjectWindowless)
{
return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult);
}
else if (m_spIOleInPlaceObject) {
HWND wnd;
if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd)))
SendMessage(wnd, msg, wParam, lParam);
}
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleControlSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock)
{
m_bInPlaceLocked = fLock;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags)
{
HRESULT hr = S_OK;
if (pPtlHimetric == NULL)
{
return E_INVALIDARG;
}
if (pPtfContainer == NULL)
{
return E_INVALIDARG;
}
HDC hdc = ::GetDC(m_hWndParent);
::SetMapMode(hdc, MM_HIMETRIC);
POINT rgptConvert[2];
rgptConvert[0].x = 0;
rgptConvert[0].y = 0;
if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER)
{
rgptConvert[1].x = pPtlHimetric->x;
rgptConvert[1].y = pPtlHimetric->y;
::LPtoDP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x);
pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y);
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtfContainer->x = (float)rgptConvert[1].x;
pPtfContainer->y = (float)rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC)
{
rgptConvert[1].x = (int)(pPtfContainer->x);
rgptConvert[1].y = (int)(pPtfContainer->y);
::DPtoLP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x;
pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y;
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtlHimetric->x = rgptConvert[1].x;
pPtlHimetric->y = rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else
{
hr = E_INVALIDARG;
}
::ReleaseDC(m_hWndParent, hdc);
return hr;
}
HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IBindStatusCallback implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved,
IBinding __RPC_FAR *pib)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress,
ULONG ulProgressMax,
ULONG ulStatusCode,
LPCWSTR szStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError)
{
m_bBindingInProgress = FALSE;
m_hrBindResult = hresult;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF,
BINDINFO __RPC_FAR *pbindInfo)
{
*pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE |
BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE;
pbindInfo->cbSize = sizeof(BINDINFO);
pbindInfo->szExtraInfo = NULL;
memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM));
pbindInfo->grfBindInfoF = 0;
pbindInfo->dwBindVerb = 0;
pbindInfo->szCustomVerb = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF,
DWORD dwSize,
FORMATETC __RPC_FAR *pformatetc,
STGMEDIUM __RPC_FAR *pstgmed)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid,
IUnknown __RPC_FAR *punk)
{
return S_OK;
}
// IWindowForBindingUI
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(
/* [in] */ REFGUID rguidReason,
/* [out] */ HWND *phwnd)
{
*phwnd = NULL;
return S_OK;
}
| 007slmg-ff | ff-activex-host/ffactivex/common/ControlSite.cpp | C++ | lgpl | 44,015 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITEIPFRAME_H
#define CONTROLSITEIPFRAME_H
class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>,
public IOleInPlaceFrame
{
public:
CControlSiteIPFrame();
virtual ~CControlSiteIPFrame();
HWND m_hwndFrame;
BEGIN_COM_MAP(CControlSiteIPFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY(IOleInPlaceFrame)
END_COM_MAP()
// IOleWindow
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleInPlaceUIWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName);
// IOleInPlaceFrame implementation
virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject);
virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText);
virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID);
};
typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance;
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/ControlSiteIPFrame.h | C++ | lgpl | 3,891 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef IOLECOMMANDIMPL_H
#define IOLECOMMANDIMPL_H
// Implementation of the IOleCommandTarget interface. The template is
// reasonably generic and reusable which is a good thing given how needlessly
// complicated this interface is. Blame Microsoft for that and not me.
//
// To use this class, derive your class from it like this:
//
// class CComMyClass : public IOleCommandTargetImpl<CComMyClass>
// {
// ... Ensure IOleCommandTarget is listed in the interface map ...
// BEGIN_COM_MAP(CComMyClass)
// COM_INTERFACE_ENTRY(IOleCommandTarget)
// // etc.
// END_COM_MAP()
// ... And then later on define the command target table ...
// BEGIN_OLECOMMAND_TABLE()
// OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page")
// OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page")
// OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode")
// END_OLECOMMAND_TABLE()
// ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ...
// HWND GetCommandTargetWindow() const
// {
// return m_hWnd;
// }
// ... Now procedures that OLECOMMAND_HANDLER calls ...
// static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
// }
//
// The command table defines which commands the object supports. Commands are
// defined by a command id and a command group plus a WM_COMMAND id or procedure,
// and a verb and short description.
//
// Notice that there are two macros for handling Ole Commands. The first,
// OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from
// GetCommandTargetWindow() (that the derived class must implement if it uses
// this macro).
//
// The second, OLECOMMAND_HANDLER calls a static handler procedure that
// conforms to the OleCommandProc typedef. The first parameter, pThis means
// the static handler has access to the methods and variables in the class
// instance.
//
// The OLECOMMAND_HANDLER macro is generally more useful when a command
// takes parameters or needs to return a result to the caller.
//
template< class T >
class IOleCommandTargetImpl : public IOleCommandTarget
{
struct OleExecData
{
const GUID *pguidCmdGroup;
DWORD nCmdID;
DWORD nCmdexecopt;
VARIANT *pvaIn;
VARIANT *pvaOut;
};
public:
typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
struct OleCommandInfo
{
ULONG nCmdID;
const GUID *pCmdGUID;
ULONG nWindowsCmdID;
OleCommandProc pfnCommandProc;
wchar_t *szVerbText;
wchar_t *szStatusText;
};
// Query the status of the specified commands (test if is it supported etc.)
virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText)
{
T* pT = static_cast<T*>(this);
if (prgCmds == NULL)
{
return E_INVALIDARG;
}
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
BOOL bCmdGroupFound = FALSE;
BOOL bTextSet = FALSE;
// Iterate through list of commands and flag them as supported/unsupported
for (ULONG nCmd = 0; nCmd < cCmds; nCmd++)
{
// Unsupported by default
prgCmds[nCmd].cmdf = 0;
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != prgCmds[nCmd].cmdID)
{
continue;
}
// Command is supported so flag it and possibly enable it
prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED;
if (pCI->nWindowsCmdID != 0)
{
prgCmds[nCmd].cmdf |= OLECMDF_ENABLED;
}
// Copy the status/verb text for the first supported command only
if (!bTextSet && pCmdText)
{
// See what text the caller wants
wchar_t *pszTextToCopy = NULL;
if (pCmdText->cmdtextf & OLECMDTEXTF_NAME)
{
pszTextToCopy = pCI->szVerbText;
}
else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS)
{
pszTextToCopy = pCI->szStatusText;
}
// Copy the text
pCmdText->cwActual = 0;
memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t));
if (pszTextToCopy)
{
// Don't exceed the provided buffer size
size_t nTextLen = wcslen(pszTextToCopy);
if (nTextLen > pCmdText->cwBuf)
{
nTextLen = pCmdText->cwBuf;
}
wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen);
pCmdText->cwActual = nTextLen;
}
bTextSet = TRUE;
}
break;
}
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return S_OK;
}
// Execute the specified command
virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut)
{
T* pT = static_cast<T*>(this);
BOOL bCmdGroupFound = FALSE;
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != nCmdID)
{
continue;
}
// Send ourselves a WM_COMMAND windows message with the associated
// identifier and exec data
OleExecData cData;
cData.pguidCmdGroup = pguidCmdGroup;
cData.nCmdID = nCmdID;
cData.nCmdexecopt = nCmdexecopt;
cData.pvaIn = pvaIn;
cData.pvaOut = pvaOut;
if (pCI->pfnCommandProc)
{
pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP)
{
HWND hwndTarget = pT->GetCommandTargetWindow();
if (hwndTarget)
{
::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData);
}
}
else
{
// Command supported but not implemented
continue;
}
return S_OK;
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return OLECMDERR_E_NOTSUPPORTED;
}
};
// Macros to be placed in any class derived from the IOleCommandTargetImpl
// class. These define what commands are exposed from the object.
#define BEGIN_OLECOMMAND_TABLE() \
OleCommandInfo *GetCommandTable() \
{ \
static OleCommandInfo s_aSupportedCommands[] = \
{
#define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \
{ id, group, cmd, NULL, verb, desc },
#define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \
{ id, group, 0, handler, verb, desc },
#define END_OLECOMMAND_TABLE() \
{ 0, &GUID_NULL, 0, NULL, NULL, NULL } \
}; \
return s_aSupportedCommands; \
};
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/IOleCommandTargetImpl.h | C++ | lgpl | 10,589 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYLIST_H
#define PROPERTYLIST_H
// A simple array class for managing name/value pairs typically fed to controls
// during initialization by IPersistPropertyBag
class PropertyList
{
struct Property {
BSTR bstrName;
VARIANT vValue;
} *mProperties;
unsigned long mListSize;
unsigned long mMaxListSize;
bool EnsureMoreSpace()
{
// Ensure enough space exists to accomodate a new item
const unsigned long kGrowBy = 10;
if (!mProperties)
{
mProperties = (Property *) malloc(sizeof(Property) * kGrowBy);
if (!mProperties)
return false;
mMaxListSize = kGrowBy;
}
else if (mListSize == mMaxListSize)
{
Property *pNewProperties;
pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy));
if (!pNewProperties)
return false;
mProperties = pNewProperties;
mMaxListSize += kGrowBy;
}
return true;
}
public:
PropertyList() :
mProperties(NULL),
mListSize(0),
mMaxListSize(0)
{
}
~PropertyList()
{
}
void Clear()
{
if (mProperties)
{
for (unsigned long i = 0; i < mListSize; i++)
{
SysFreeString(mProperties[i].bstrName); // Safe even if NULL
VariantClear(&mProperties[i].vValue);
}
free(mProperties);
mProperties = NULL;
}
mListSize = 0;
mMaxListSize = 0;
}
unsigned long GetSize() const
{
return mListSize;
}
const BSTR GetNameOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return mProperties[nIndex].bstrName;
}
const VARIANT *GetValueOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return &mProperties[nIndex].vValue;
}
bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName)
return false;
for (unsigned long i = 0; i < GetSize(); i++)
{
// Case insensitive
if (wcsicmp(mProperties[i].bstrName, bstrName) == 0)
{
return SUCCEEDED(
VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue)));
}
}
return AddNamedProperty(bstrName, vValue);
}
bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName || !EnsureMoreSpace())
return false;
Property *pProp = &mProperties[mListSize];
pProp->bstrName = ::SysAllocString(bstrName);
if (!pProp->bstrName)
{
return false;
}
VariantInit(&pProp->vValue);
if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue))))
{
SysFreeString(pProp->bstrName);
return false;
}
mListSize++;
return true;
}
};
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/PropertyList.h | C++ | lgpl | 5,004 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ITEMCONTAINER_H
#define ITEMCONTAINER_H
// typedef std::map<tstring, CIUnkPtr> CNamedObjectList;
// Class for managing a list of named objects.
class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>,
public IOleItemContainer
{
// CNamedObjectList m_cNamedObjectList;
public:
CItemContainer();
virtual ~CItemContainer();
BEGIN_COM_MAP(CItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer)
END_COM_MAP()
// IParseDisplayName implementation
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut);
// IOleContainer implementation
virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum);
virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock);
// IOleItemContainer implementation
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage);
virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem);
};
typedef CComObject<CItemContainer> CItemContainerInstance;
#endif | 007slmg-ff | ff-activex-host/ffactivex/common/ItemContainer.h | C++ | lgpl | 3,631 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType); | 007slmg-ff | ff-activex-host/ffactivex/authorize.h | C | lgpl | 2,050 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winbase.h>
// ----------------------------------------------------------------------------
int main (int ArgC,
char *ArgV[])
{
const char *sourceName;
const char *targetName;
HANDLE targetHandle;
void *versionPtr;
DWORD versionLen;
int lastError;
int ret = 0;
if (ArgC < 3) {
fprintf(stderr,
"Usage: %s <source> <target>\n",
ArgV[0]);
exit (1);
}
sourceName = ArgV[1];
targetName = ArgV[2];
if ((versionLen = GetFileVersionInfoSize(sourceName,
NULL)) == 0) {
fprintf(stderr,
"Could not retrieve version len from %s\n",
sourceName);
exit (2);
}
if ((versionPtr = calloc(1,
versionLen)) == NULL) {
fprintf(stderr,
"Error allocating temp memory\n");
exit (3);
}
if (!GetFileVersionInfo(sourceName,
NULL,
versionLen,
versionPtr)) {
fprintf(stderr,
"Could not retrieve version info from %s\n",
sourceName);
exit (4);
}
if ((targetHandle = BeginUpdateResource(targetName,
FALSE)) == INVALID_HANDLE_VALUE) {
fprintf(stderr,
"Could not begin update of %s\n",
targetName);
free(versionPtr);
exit (5);
}
if (!UpdateResource(targetHandle,
RT_VERSION,
MAKEINTRESOURCE(VS_VERSION_INFO),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
versionPtr,
versionLen)) {
lastError = GetLastError();
fprintf(stderr,
"Error %d updating resource\n",
lastError);
ret = 6;
}
if (!EndUpdateResource(targetHandle,
FALSE)) {
fprintf(stderr,
"Error finishing update\n");
ret = 7;
}
free(versionPtr);
return (ret);
}
| 007slmg-ff | ff-activex-host/transver/transver.cpp | C++ | lgpl | 3,963 |
<html>
<head>
</head>
<body>
<script language="JavaScript">
function Test() {
var result = plugin.invoke("<QueryStatus />");
alert(result);
}
/* instantiate the plugin */
var plugin = document.createElement("object");
plugin.setAttribute("type", "application/x-itst-activex");
plugin.setAttribute("progid", "prodown.GenRSJ");
document.body.appendChild(plugin);
window.setTimeout("Test()", 100);
</script>
<button onclick="Test()">Test</button>
</body>
</html> | 007slmg-ff | ff-activex-host/test.html | HTML | lgpl | 571 |
setlocal
cd install
"c:\Program Files\Inno Setup 5\iscc" /O../dist /dxversion=%1 /dxbasepath=../ ffactivex.iss
cd ..
copy dist\ffactivex-setup.exe dist\ffactivex-setup-%1.exe
endlocal
| 007slmg-ff | ff-activex-host/tool/mkinst.cmd | Batchfile | lgpl | 200 |
#ifndef MyAppName
#define MyAppName "Firefox ActiveX Plugin"
#endif
#ifndef MyAppURL
#define MyAppURL "http://code.google.com/p/ff-activex-host/"
#endif
#ifndef xversion
#define xversion "r37"
#endif
#ifndef xbasepath
#define xbasepath "c:\src\ff-activex-host\ff-activex-host\"
#endif
[Setup]
AppId={{97F2985C-B74A-4672-960E-E3769AE5657A}}
AppName={#MyAppName}
AppVerName={#MyAppName} {#xversion}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DefaultGroupName={#MyAppName}
OutputBaseFilename=ffactivex-setup
Compression=lzma
SolidCompression=yes
InternalCompressLevel=ultra
ArchitecturesInstallIn64BitMode=x64 ia64
#include "ffactivex.inc"
[Registry]
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\clsid\*"; ValueType: string; ValueName: "*"; ValueData: true;
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\progid\*"; ValueType: string; ValueName: "*"; ValueData: true;
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\codeBaseUrl\*"; ValueType: string; ValueName: "*"; ValueData: true;
[Files]
Source: {#xbasepath}\Release\transver.exe; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete
| 007slmg-ff | ff-activex-host/install/ffactivex.iss | Inno Setup | lgpl | 1,415 |
[Files]
Source: {#xbasepath}\Release\npffax.dll; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete
[Registry]
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; Flags: uninsdeletekey
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Description; ValueData: {#MyAppName} {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: ProductName; ValueData: {#MyAppName} {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Path; ValueData: {app}\npffax.dll
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Version; ValueData: {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes; ValueType: string; ValueName: Dummy; ValueData: {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex; ValueType: string; ValueName: "Dummy"; ValueData: "{#xversion}" | 007slmg-ff | ff-activex-host/install/ffactivex.inc | C++ | lgpl | 1,366 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
public class Robot extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
}
/**
* Initialization code for disabled mode should go here
*/
public void disabledInit() {
}
/**
* Initialization code for autonomous mode should go here.
*/
public void autonomousInit() {
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* Initialization code for teleop mode should go here.
*/
public void teleopInit() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Robot.java | Java | bsd | 1,663 |
package edu.wpi.first.wpilibj.templates.AxisCamera;
/**
* Camera.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Camera {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/AxisCamera/Camera.java | Java | bsd | 162 |
package edu.wpi.first.wpilibj.templates.Solenoid;
/**
* Solenoid.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Solenoid {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Solenoid/Solenoid.java | Java | bsd | 164 |
package edu.wpi.first.wpilibj.templates.OperatorInput;
/**
* Joystick.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Joystick {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/OperatorInput/Joystick.java | Java | bsd | 169 |
package edu.wpi.first.wpilibj.templates.OperatorInput;
/**
* Xbox.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Xbox {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/OperatorInput/Xbox.java | Java | bsd | 161 |
package edu.wpi.first.wpilibj.templates.Relay;
/**
* SpikeRelay.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class SpikeRelay {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Relay/SpikeRelay.java | Java | bsd | 165 |
package edu.wpi.first.wpilibj.templates.MotorControllers;
/**
* Jaguar.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Jaguar {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/MotorControllers/Jaguar.java | Java | bsd | 168 |
package edu.wpi.first.wpilibj.templates.MotorControllers;
/**
* Talon.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Talon {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/MotorControllers/Talon.java | Java | bsd | 166 |
package edu.wpi.first.wpilibj.templates.MotorControllers;
/**
* Victor.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Victor {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/MotorControllers/Victor.java | Java | bsd | 168 |
package edu.wpi.first.wpilibj.templates;
/**
* RobotMap.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
/*
* Map DIO, AIO, Etc. to public variables
*/
public class RobotMap {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/RobotMap.java | Java | bsd | 206 |
package edu.wpi.first.wpilibj.templates.Sensors;
/**
* RotaryQuadEncoder.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class RotaryQuadEncoder {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Sensors/RotaryQuadEncoder.java | Java | bsd | 181 |
package edu.wpi.first.wpilibj.templates.Sensors;
/**
* Potentiometer.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Potentiometer {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Sensors/Potentiometer.java | Java | bsd | 173 |
package edu.wpi.first.wpilibj.templates.Sensors;
/**
* LimitSwitch.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class LimitSwitch {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Sensors/LimitSwitch.java | Java | bsd | 169 |
package edu.wpi.first.wpilibj.templates.Sensors;
/**
* RangeFinder.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class RangeFinder {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Sensors/RangeFinder.java | Java | bsd | 169 |
package edu.wpi.first.wpilibj.templates.Sensors;
/**
* Gyro.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Gyro {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Sensors/Gyro.java | Java | bsd | 155 |
package edu.wpi.first.wpilibj.templates;
/**
* DSMap.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
/*
* Driver Station map. Map DS inputs to variables.
*/
public class DSMap {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/DSMap.java | Java | bsd | 208 |
package edu.wpi.first.wpilibj.templates.Subsystems;
/**
* Drivetrain.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Drivetrain {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Subsystems/Drivetrain.java | Java | bsd | 170 |
package edu.wpi.first.wpilibj.templates.Subsystems;
/**
* Compressor.java
* Created on Jan 5, 2014
* Author Joe Porter
* Team 1247
*/
public class Compressor {
}
| 1247-robot-classes-2014 | src/edu/wpi/first/wpilibj/templates/Subsystems/Compressor.java | Java | bsd | 170 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DAO;
namespace BUS
{
public class RuleObjectBUS
{
RuleObjectDAO RuleDAO = new RuleObjectDAO();
public bool InsertRuleOfGroup(int ID)
{
return RuleDAO.InsertRuleOfGroup(ID);
}
public bool CheckPermission(int groupID, int RuleID)
{
return RuleDAO.CheckPermission(groupID, RuleID);
}
public List<RuleObjectDTO> GetListRuleObject(int id)
{
return RuleDAO.GetListRuleObject(id);
}
public bool UpdateRuleObject(List<RuleObjectDTO> listRule)
{
return RuleDAO.UpdateRuleObject(listRule);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/RuleObjectBUS.cs | C# | asf20 | 795 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DAO;
using System.ComponentModel;
namespace BUS
{
public class AccountBUS
{
AccountDAO AccDAO = new AccountDAO();
public int InsertAccount(AccountDTO Acc)
{
return AccDAO.InsertAccount(Acc);
}
public bool UpdateAccount(AccountDTO Acc)
{
return AccDAO.UpdateAccount(Acc);
}
public bool DeleteAccount(int ID)
{
return AccDAO.DeleteAccount(ID);
}
public BindingList<AccountDTO> GetNewBindingList()
{
return AccDAO.GetNewBindingList();
}
public AccountDTO GetAccountByID(int ID)
{
return AccDAO.GetAccountByID(ID);
}
public bool Login(string userName, string password,out AccountDTO acc)
{
return AccDAO.Login(userName, password, out acc);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/AccountBUS.cs | C# | asf20 | 1,036 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
namespace BUS
{
public class DocSequenceBUS
{
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
/// <summary>
/// Get DocSequence By Name of DocSequence
/// </summary>
/// <param name="name">Name of DocSequence</param>
/// <returns>DocSequenceDTO</returns>
public DocSequenceDTO GetDocSequenceByName(String name)
{
return docSeqDAO.GetDocSequenceByName(name);
}
public bool CheckDocSequenceExists(string code)
{
return docSeqDAO.CheckDocSequenceExists(code);
}
public bool UpdateNextDocSequence(string name)
{
return docSeqDAO.UpdateNextDocSequence(name);
}
public bool UpdateDocSequence(DocSequenceDTO doc)
{
return docSeqDAO.UpdateDocSequence(doc);
}
public bool UpdateDocSequence(List<DocSequenceDTO> listDocSeq)
{
try
{
bool isSucces = true;
foreach (DocSequenceDTO doc in listDocSeq)
{
isSucces = docSeqDAO.UpdateDocSequence(doc);
}
return isSucces;
}
catch
{
return false;
}
}
public string GetNextDocSequenceNumber(string name)
{
return docSeqDAO.GetNextDocSequenceNumber(name);
}
public List<DocSequenceDTO> GetListDocSequence()
{
return docSeqDAO.GetListDocSequence();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/DocSequenceBUS.cs | C# | asf20 | 1,756 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DAO;
using System.ComponentModel;
namespace BUS
{
public class ParameterBUS
{
ParameterDAO parameterDAO = new ParameterDAO();
public int GetParameterValueByCode(string code)
{
return parameterDAO.GetParameterValueByCode(code);
}
public ParameterDTO GetParameterByID(int id)
{
return parameterDAO.GetParameterByID(id);
}
public int InsertParameter(ParameterDTO paramDto)
{
if (parameterDAO.CheckExistsCode(paramDto.ParameterCode))
{
return 0;
}
return parameterDAO.InsertParameter(paramDto);
}
public List<ParameterDTO> GetParameterList()
{
return parameterDAO.GetParameterList();
}
public bool CheckExistsCode(string code)
{
return parameterDAO.CheckExistsCode(code);
}
public bool UpdateParameter(ParameterDTO paramDTO)
{
return parameterDAO.UpdateParameter(paramDTO);
}
public BindingList<ParameterDTO> GetNewBindingListParameter()
{
return parameterDAO.GetNewBindingListParameter();
}
public bool DeleteParameter(int ID)
{
return parameterDAO.DeleteParameter(ID);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/ParameterBUS.cs | C# | asf20 | 1,511 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using DTO;
using DAO;
namespace BUS
{
public class BookBUS
{
BookDAO bookDAO = new BookDAO();
public BindingList<BookDTO> GetNewBindingList()
{
return bookDAO.GetNewBindingList();
}
public int InsertBook(BookDTO bookDto)
{
if (bookDAO.CheckExistsCode(bookDto.BookCode))
{
return 0;
}
return bookDAO.InsertBook(bookDto);
}
public bool UpdateBook(BookDTO bookDto)
{
return bookDAO.UpdateBook(bookDto);
}
public BookDTO GetBookByID(int ID)
{
return bookDAO.GetBookByID(ID);
}
public bool DeleteBook(int ID)
{
return bookDAO.DeleteBook(ID);
}
public List<BookReportDTO> GetListBookForReport(DateTime from, DateTime to)
{
return bookDAO.GetListBookForReport(from, to);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/BookBUS.cs | C# | asf20 | 1,132 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DAO;
using System.ComponentModel;
namespace BUS
{
public class UsersGroupBUS
{
UsersGroupDAO userGrDAO = new UsersGroupDAO();
public int InsertUsersGroup(UsersGroupDTO userGroup)
{
return userGrDAO.InsertUsersGroup(userGroup);
}
public List<UsersGroupDTO> GetUsersGroupList()
{
return userGrDAO.GetUsersGroupList();
}
public bool CheckExistsCode(string code)
{
return userGrDAO.CheckExistsCode(code);
}
public bool UpdateUsersGroup(UsersGroupDTO userDTO)
{
return userGrDAO.UpdateUsersGroup(userDTO);
}
public UsersGroupDTO GetUsersGroupByID(int userID)
{
return userGrDAO.GetUsersGroupByID(userID);
}
public BindingList<UsersGroupDTO> GetNewBindingListUsersGroup()
{
return userGrDAO.GetNewBindingListUsersGroup();
}
public bool DeleteUsersGroup(int userID)
{
return userGrDAO.DeleteUsersGroup(userID);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/UsersGroupBUS.cs | C# | asf20 | 1,246 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
namespace BUS
{
public class ReceivingBUS
{
ReceivingDAO receiDAO = new ReceivingDAO();
public bool InsertReceivingList(ReceivingListDTO receiDto)
{
try
{
receiDto.ReceivingID = receiDAO.InsertReceiving(receiDto);
if (receiDto.ReceivingID > 0)
{
foreach (ReceivingDetailDTO receiDetail in receiDto.ListReceiving)
{
receiDetail.ReceivingID = receiDto.ReceivingID;
receiDetail.ReceivingDetailID = receiDAO.InsertReceivingDetail(receiDetail);
BookDAO bookDAO = new BookDAO();
bookDAO.UpdateQuantityFromReceiving(receiDetail.BookID, receiDetail.Quantity);
}
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public bool CheckQuantityReceiving(int quantity)
{
ParameterDAO paraDAO = new ParameterDAO();
int paraQuantity = paraDAO.GetParameterValueByCode(ParameterCode.MaxReceiving.ToString());
if (quantity > paraQuantity)
{
return false;
}
else
{
return true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/ReceivingBUS.cs | C# | asf20 | 1,661 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DAO;
using System.ComponentModel;
namespace BUS
{
public class AuthorBUS
{
AuthorDAO authorDAO = new AuthorDAO();
public int InsertAuthor(AuthorDTO author)
{
if (authorDAO.CheckExistsCode(author.AuthorCode))
{
return 0;
}
return authorDAO.InsertAuthor(author);
}
public bool CheckExistsCode(string code)
{
return authorDAO.CheckExistsCode(code);
}
public BindingList<AuthorDTO> GetNewBindingListAuthor()
{
return authorDAO.GetNewBindingListAuthor();
}
public bool UpdateAuthor(AuthorDTO author)
{
return authorDAO.UpdateAuthor(author);
}
public AuthorDTO GetAuthorByID(int id)
{
return authorDAO.GetAuthorByID(id);
}
public bool DeleteAuthor(int authorID)
{
if (authorDAO.CheckRelation(authorID))
{
return false;
}
return authorDAO.DeleteAuthor(authorID);
}
public void DeleteAuthor(List<int> authorID,out int success,out int fail)
{
success = 0;
fail = 0;
foreach (int id in authorID)
{
if (authorDAO.CheckRelation(id))
{
fail++;
}
else
{
if (authorDAO.DeleteAuthor(id))
{
success++;
}
else
{
fail++;
}
}
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/AuthorBUS.cs | C# | asf20 | 1,915 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
namespace BUS
{
public class InvoiceBUS
{
InvoiceDAO invoiceDAO = new InvoiceDAO();
public bool CheckQuantityStockAfterSell(int quantity)
{
try
{
ParameterDAO paraDAO = new ParameterDAO();
int stockquantity = paraDAO.GetParameterValueByCode(ParameterCode.MinAfterSell.ToString());
if (quantity < stockquantity)
{
return false;
}
else
{
return true;
}
}
catch
{
return false;
}
}
public bool InsertInvoiceList(InvoiceDTO invoice)
{
try
{
invoice.InvoiceID = invoiceDAO.InsertInvoice(invoice);
if (invoice.InvoiceID > 0)
{
foreach (InvoiceDetailDTO invoiceDetail in invoice.ListInvoiceDetail)
{
invoiceDetail.InvoiceID = invoice.InvoiceID;
invoiceDetail.InvoiceDetailID = invoiceDAO.InsertInvoiceDetail(invoiceDetail);
BookDAO bookDAO = new BookDAO();
bookDAO.UpdateQuantityFromReceiving(invoiceDetail.BookID, -invoiceDetail.Quantity);
}
CustomerBUS customerBUS = new CustomerBUS();
customerBUS.UpdateCustomerDebtFromInvoice(invoice.CustomerID, invoice.GrandTotal);
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/InvoiceBUS.cs | C# | asf20 | 1,993 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
namespace BUS
{
public class PayMoneyBUS
{
PayMoneyDAO paymoneyDao = new PayMoneyDAO();
public int InsertPayMoney(PayMoneyDTO pmDto)
{
return paymoneyDao.InsertPayMoney(pmDto);
}
public bool UpdatePayMoney(PayMoneyDTO pmDto)
{
return paymoneyDao.UpdatePayMoney(pmDto);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/PayMoneyBUS.cs | C# | asf20 | 503 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BUS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BUS")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("81c3151d-5f4c-4392-a0fc-ac71761fb71b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/Properties/AssemblyInfo.cs | C# | asf20 | 1,418 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
using System.ComponentModel;
namespace BUS
{
public class CategoryBUS
{
CategoryDAO categoryDao = new CategoryDAO();
public int InsertCategory(CategoryDTO categoryDto)
{
if (categoryDao.CheckExistsCode(categoryDto.CategoryCode))
{
return 0;
}
return categoryDao.InsertCategory(categoryDto);
}
public List<CategoryDTO> GetCategoryList()
{
return categoryDao.GetCategoryList();
}
public bool CheckExistsCode(string code)
{
return categoryDao.CheckExistsCode(code);
}
public bool UpdateCategory(CategoryDTO cateDTO)
{
return categoryDao.UpdateCategory(cateDTO);
}
public CategoryDTO GetCategoryByID(int cateID)
{
return categoryDao.GetCategoryByID(cateID);
}
public BindingList<CategoryDTO> GetNewBindingListCategory()
{
return categoryDao.GetNewBindingListCategory();
}
public bool DeleteCategory(int cateID)
{
return categoryDao.DeleteCategory(cateID);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/CategoryBUS.cs | C# | asf20 | 1,353 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
using System.ComponentModel;
namespace BUS
{
public class EmployeeBUS
{
EmployeeDAO EmployeeDao = new EmployeeDAO();
public int InsertEmployee(EmployeeDTO employeeDto)
{
if (EmployeeDao.CheckExistsCode(employeeDto.EmployeeCode))
{
return 0;
}
return EmployeeDao.InsertEmployee(employeeDto);
}
public List<EmployeeDTO> GetEmployeeList()
{
return EmployeeDao.GetEmployeeList();
}
public bool CheckExistsCode(string code)
{
return EmployeeDao.CheckExistsCode(code);
}
public bool UpdateEmployee(EmployeeDTO empDTO)
{
return EmployeeDao.UpdateEmployee(empDTO);
}
public EmployeeDTO GetEmployeeByID(int empID)
{
return EmployeeDao.GetEmployeeByID(empID);
}
public BindingList<EmployeeDTO> GetNewBindingListEmployee()
{
return EmployeeDao.GetNewBindingListEmployee();
}
public bool DeleteEmployee(int empID)
{
return EmployeeDao.DeleteEmployee(empID);
}
public List<UsersGroupDTO> Load_UserGroup()
{
return EmployeeDao.Load_UserGroup();
}
public List<EmployeeDTO> GetEmployeeListNotHasAccount()
{
return EmployeeDao.GetEmployeeNotHasAccount();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/EmployeeBUS.cs | C# | asf20 | 1,625 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;
using System.ComponentModel;
namespace BUS
{
public class CustomerBUS
{
CustomerDAO customerDao = new CustomerDAO();
public int InsertCustomer(CustomerDTO cusDto)
{
if (customerDao.CheckExistsCode(cusDto.CustomerCode))
{
return 0;
}
return customerDao.InsertCustomer(cusDto);
}
public List<CustomerDTO> GetCustomerList()
{
return customerDao.GetCustomerList();
}
public bool CheckExistsCode(string code)
{
return customerDao.CheckExistsCode(code);
}
public bool UpdateCustomer(CustomerDTO cusDTO)
{
return customerDao.UpdateCustomer(cusDTO);
}
public bool UpdateCustomerDebtMoney(int cusID, double debtMoney)
{
return customerDao.UpdateCustomerDebtMoney(cusID, debtMoney);
}
public CustomerDTO GetCustomerByID(int ID)
{
return customerDao.GetCustomerByID(ID);
}
public BindingList<CustomerDTO> GetNewBindingListCustomer()
{
return customerDao.GetNewBindingListCustomer();
}
public bool DeleteCustomer(int ID)
{
return customerDao.DeleteCustomer(ID);
}
public CustomerDTO GetCustomerByCode(string code)
{
return customerDao.GetCustomerByCode(code);
}
public bool CheckCustomerDebt(CustomerDTO customer)
{
ParameterBUS paraBUS = new ParameterBUS();
float MaxDebt = paraBUS.GetParameterValueByCode(ParameterCode.MaxDebt.ToString());
if (customer.CustomerDebtMoney > MaxDebt)
{
return false;
}
else
{
return true;
}
}
public bool UpdateCustomerDebtFromInvoice(int id, float total)
{
return customerDao.UpdateCustomerDebtFromInvoice(id, total);
}
public List<CustomerReportDTO> GetListCustomerForReport(int month)
{
return customerDao.GetListCustomerForReport(month);
}
public List<CustomerReportDTO> GetListCustomerForReport(int customerID, int month)
{
return customerDao.GetListCustomerForReport(customerID, month);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/BUS/CustomerBUS.cs | C# | asf20 | 2,596 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
namespace DAO
{
public class DocSequenceDAO
{
private DocSequenceDTO CreateDocSeqDTOFromEntity(MaSoChungTu ms)
{
DocSequenceDTO docSeq = new DocSequenceDTO
{
DocSequenceID = ms.MaSoID,
DocSequenceCode = ms.MaSoCode,
DocSequenceName = ms.MaSoName,
DocSequenceText = ms.MaSoText,
Separator = ms.DauPhanCach,
CurrentNum = ms.SoHienTai ?? 0,
Middle = ms.Giua,
NumLength = ms.DoDaiSo ?? 0,
DocSequenceTemp = GetNextDocSequenceNumber(ms.MaSoName)
};
return docSeq;
}
/// <summary>
/// Get DocSequence By Name of DocSequence
/// </summary>
/// <param name="name">Name of DocSequence</param>
/// <returns>DocSequenceDTO</returns>
public DocSequenceDTO GetDocSequenceByName(string name)
{
MaSoChungTu doc;
using (BookStoreEntities ent = new BookStoreEntities())
{
doc = ent.MaSoChungTus.FirstOrDefault(m => m.MaSoName == name);
if (doc == null)
{
return null;
}
}
DocSequenceDTO docSequence = CreateDocSeqDTOFromEntity(doc);
return docSequence;
}
public bool CheckDocSequenceExists(string code)
{
int count = 0;
using (BookStoreEntities ent = new BookStoreEntities())
{
ent.MaSoChungTus.Where(m => m.MaSoCode == code).Count();
}
if (count > 0)
{
return true;
}
else
{
return false;
}
}
public bool UpdateNextDocSequence(string name)
{
using(BookStoreEntities ent = new BookStoreEntities())
{
MaSoChungTu doc = ent.MaSoChungTus.FirstOrDefault(m => m.MaSoName == name);
if (doc == null)
{
return false;
}
doc.SoHienTai += 1;
ent.SaveChanges();
return true;
}
}
public bool UpdateDocSequence(DocSequenceDTO doc)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
MaSoChungTu msct = ent.MaSoChungTus.FirstOrDefault(m => m.MaSoID == doc.DocSequenceID);
if (msct == null)
{
return false;
}
msct.MaSoCode = doc.DocSequenceCode;
msct.DoDaiSo = doc.NumLength;
msct.Giua = doc.Middle;
msct.DauPhanCach = doc.Separator;
ent.SaveChanges();
return true;
}
}
public string GetNextDocSequenceNumber(string name)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
MaSoChungTu doc = ent.MaSoChungTus.FirstOrDefault(m => m.MaSoName == name);
if(doc == null)
{
return string.Empty;
}
string nextNum = string.Empty;
string format = string.Empty;
int length = int.Parse(doc.DoDaiSo.ToString());
for (int i = 0; i < length; i++)
{
format += "0";
}
int curNum = int.Parse(doc.SoHienTai.ToString());
nextNum = (curNum + 1).ToString(format);
string code = string.Empty;
if (doc.Giua != null && !string.IsNullOrEmpty(doc.Giua))
{
code = string.Format("{0}{1}{2}{3}{4}", doc.MaSoCode, doc.DauPhanCach, doc.Giua, doc.DauPhanCach, nextNum);
}
else
{
code = doc.MaSoCode + doc.DauPhanCach + nextNum;
}
return code;
}
}
public List<DocSequenceDTO> GetListDocSequence()
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
List<MaSoChungTu> listMSCT = ent.MaSoChungTus.ToList();
List<DocSequenceDTO> listDocSeq = new List<DocSequenceDTO>();
foreach (MaSoChungTu msct in listMSCT)
{
listDocSeq.Add(CreateDocSeqDTOFromEntity(msct));
}
return listDocSeq;
}
}
catch
{
return null;
}
}
public string GetNextDocSequenceNumber(int id)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
MaSoChungTu doc = ent.MaSoChungTus.FirstOrDefault(m => m.MaSoID == id);
if (doc == null)
{
return string.Empty;
}
string nextNum = string.Empty;
string format = string.Empty;
int length = int.Parse(doc.DoDaiSo.ToString());
for (int i = 0; i < length; i++)
{
format += "0";
}
int curNum = int.Parse(doc.SoHienTai.ToString());
nextNum = (curNum + 1).ToString(format);
string code = string.Empty;
if (doc.Giua != null && !string.IsNullOrEmpty(doc.Giua))
{
code = string.Format("{0}{1}{2}{3}{4}", doc.MaSoCode, doc.DauPhanCach, doc.Giua, doc.DauPhanCach, nextNum);
}
else
{
code = doc.MaSoCode + doc.DauPhanCach + nextNum;
}
return code;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/DocSequenceDAO.cs | C# | asf20 | 6,359 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
namespace DAO
{
public class InvoiceDAO
{
public InvoiceDTO CreateInvoiceDTOFromEntity(HoaDon hd)
{
InvoiceDTO invoiceDto = new InvoiceDTO
{
InvoiceID = hd.HoaDonID,
InvoiceCode = hd.MaHoaDon,
CustomerID = hd.KhachHangID ?? 0,
CreatedDate = hd.NgayLap ?? DateTime.Now,
CreatedBy = hd.NguoiLap ?? 0,
GrandTotal = float.Parse( hd.TongTien.ToString()),
Description = hd.GhiChu,
Status = bool.Parse(hd.SuDung.ToString())
};
using (BookStoreEntities ent = new BookStoreEntities())
{
invoiceDto.CustomerName = ent.KhachHangs.FirstOrDefault(k => k.KhachHangID == invoiceDto.CustomerID).HoTen;
}
return invoiceDto;
}
public int InsertInvoice(InvoiceDTO invoice)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
HoaDon hd = new HoaDon
{
MaHoaDon = invoice.InvoiceCode,
KhachHangID = invoice.CustomerID,
NgayLap = invoice.CreatedDate,
NguoiLap = invoice.CreatedBy,
TongTien = invoice.GrandTotal,
GhiChu = invoice.Description,
SuDung = invoice.Status
};
if (ent.HoaDons.Count(t => t.HoaDonID != null) > 0)
{
hd.HoaDonID = ent.HoaDons.Max(t => t.HoaDonID) + 1;
}
else
{
hd.HoaDonID = 1;
}
ent.AddToHoaDons(hd);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Invoice.ToString());
ent.SaveChanges();
return hd.HoaDonID;
}
}
catch
{
return -1;
}
}
public int InsertInvoiceDetail(InvoiceDetailDTO invoiceDetail)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ChiTietHoaDon cthd = new ChiTietHoaDon
{
HoaDonID = invoiceDetail.InvoiceID,
SachID = invoiceDetail.BookID,
SoLuong = invoiceDetail.Quantity,
GiaBan = invoiceDetail.UnitPrice
};
if (ent.ChiTietHoaDons.Count(t => t.ChiTietID != null) > 0)
{
cthd.ChiTietID = ent.ChiTietHoaDons.Max(t => t.ChiTietID) + 1;
}
else
{
cthd.ChiTietID = 1;
}
ent.AddToChiTietHoaDons(cthd);
ent.SaveChanges();
return cthd.ChiTietID;
}
}
catch
{
return -1;
}
}
public int GetQuantitySellForReport(int bookID, DateTime from, DateTime to)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int quantity = 0;
List<HoaDon> listInvoice = ent.HoaDons.Where(h => h.NgayLap >= from && h.NgayLap <= to).ToList();
foreach (HoaDon hd in listInvoice)
{
quantity += ent.ChiTietHoaDons.Where(c => c.HoaDonID == hd.HoaDonID && c.SachID == bookID).First().SoLuong ?? 0;
}
return quantity;
}
}
public int GetTotalBuy(int customerID, int month)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int year = DateTime.Now.Year;
List<HoaDon> hds = ent.HoaDons.Where(c => c.KhachHangID == customerID && DateTime.Parse(c.NgayLap.ToString()).Month == month && DateTime.Parse(c.NgayLap.ToString()).Year == year).ToList();
int total = 0;
foreach (HoaDon hd in hds)
{
total += (int)hd.TongTien;
}
return total;
}
}
catch
{
return 0;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/InvoiceDAO.cs | C# | asf20 | 4,971 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
namespace DAO
{
public class ReceivingDAO
{
private ReceivingListDTO CreateReceivingFromEntity(PhieuNhap pn)
{
ReceivingListDTO receivingDto = new ReceivingListDTO
{
ReceivingID = pn.PhieuNhapID,
ReceivingCode = pn.MaPhieuNhap,
ReceivingDate = pn.NgayNhap ?? DateTime.Now,
CreatedBy = pn.NguoiLap ?? 0,
GrandTotal = float.Parse( pn.TongTien.ToString()),
Description = pn.GhiChu ?? string.Empty,
Status = pn.SuDung ?? false
};
using (BookStoreEntities ent = new BookStoreEntities())
{
NhanVien nv = ent.NhanViens.First(n => n.NhanVienID == pn.NguoiLap);
receivingDto.CreatorName = nv.HoTen;
}
return receivingDto;
}
public int InsertReceiving(ReceivingListDTO receiDto)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
PhieuNhap pn = new PhieuNhap
{
MaPhieuNhap = receiDto.ReceivingCode,
NgayNhap = receiDto.ReceivingDate,
TongTien = receiDto.GrandTotal,
NguoiLap = receiDto.CreatedBy,
SuDung = receiDto.Status,
GhiChu = receiDto.Description
};
if (ent.PhieuNhaps.Count(t => t.PhieuNhapID != null) > 0)
{
pn.PhieuNhapID = ent.PhieuNhaps.Max(t => t.PhieuNhapID) + 1;
}
else
{
pn.PhieuNhapID = 1;
}
ent.AddToPhieuNhaps(pn);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Receiving.ToString());
ent.SaveChanges();
return pn.PhieuNhapID;
}
}
catch
{
return -1;
}
}
public int InsertReceivingDetail(ReceivingDetailDTO receiDetail)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ChiTietPhieuNhap ctpn = new ChiTietPhieuNhap
{
PhieuNhapID = receiDetail.ReceivingID,
SachID = receiDetail.BookID,
SoLuong = receiDetail.Quantity,
DonGia = receiDetail.UnitPrice
};
if (ent.ChiTietPhieuNhaps.Count(t => t.ChiTietID != null) > 0)
{
ctpn.ChiTietID = ent.ChiTietPhieuNhaps.Max(t => t.ChiTietID) + 1;
}
else
{
ctpn.ChiTietID = 1;
}
ent.AddToChiTietPhieuNhaps(ctpn);
ent.SaveChanges();
return ctpn.ChiTietID;
}
}
catch
{
return -1;
}
}
public int GetReceivingQuantity(int bookID, DateTime from, DateTime to)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int quantity = 0;
List<PhieuNhap> listReceive = ent.PhieuNhaps.Where(s => s.NgayNhap >= from && s.NgayNhap <= to).ToList();
foreach (PhieuNhap pn in listReceive)
{
quantity += ent.ChiTietPhieuNhaps.First(p => p.PhieuNhapID == pn.PhieuNhapID && p.SachID == bookID).SoLuong ?? 0;
}
return quantity;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/ReceivingDAO.cs | C# | asf20 | 4,194 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data.Sql;
using System.Data.SqlClient;
using System.ComponentModel;
namespace DAO
{
public class AuthorDAO
{
public int InsertAuthor(AuthorDTO authorDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TacGia authorInt = new TacGia
{
MaTacGia = authorDTO.AuthorCode,
TenTacGia = authorDTO.AuthorName,
SuDung = true
};
if (ent.TacGias.Count(t => t.TacGiaID != null) > 0)
{
authorInt.TacGiaID = ent.TacGias.Max(t => t.TacGiaID) + 1;
}
else
{
authorInt.TacGiaID = 1;
}
ent.AddToTacGias(authorInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Author.ToString());
ent.SaveChanges();
return authorInt.TacGiaID;
}
}
catch (Exception ex)
{
Utility.LogEx(ex);
return 0;
}
}
public AuthorDTO CreateAuthorDTOFromEntity(TacGia tacGia)
{
AuthorDTO authorDto = new AuthorDTO
{
AuthorID = tacGia.TacGiaID,
AuthorCode = tacGia.MaTacGia,
AuthorName = tacGia.TenTacGia,
Status = bool.Parse(tacGia.SuDung.ToString())
};
return authorDto;
}
public List<AuthorDTO> GetAuthorList()
{
List<AuthorDTO> listAuthorDto = new List<AuthorDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<TacGia> listTacGia = ent.TacGias.Where(a => a.SuDung == true).ToList();
foreach (TacGia item in listTacGia)
{
AuthorDTO authorDto = CreateAuthorDTOFromEntity(item);
listAuthorDto.Add(authorDto);
}
}
return listAuthorDto;
}
public BindingList<AuthorDTO> GetNewBindingListAuthor()
{
BindingList<AuthorDTO> listAuthorDto = new BindingList<AuthorDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<TacGia> listTacGia = ent.TacGias.Where(a => a.SuDung == true).ToList();
foreach (TacGia item in listTacGia)
{
AuthorDTO authorDto = CreateAuthorDTOFromEntity(item);
listAuthorDto.Add(authorDto);
}
}
return listAuthorDto;
}
public bool UpdateAuthor(AuthorDTO authorDto)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TacGia author = ent.TacGias.FirstOrDefault(c => c.TacGiaID == authorDto.AuthorID);
author.TenTacGia = authorDto.AuthorName;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public AuthorDTO GetAuthorByID(int id)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TacGia author = ent.TacGias.FirstOrDefault(c => c.TacGiaID == id);
AuthorDTO authDto = new AuthorDTO
{
AuthorID = author.TacGiaID,
AuthorCode = author.MaTacGia,
AuthorName = author.TenTacGia,
Status = bool.Parse(author.SuDung.ToString())
};
return authDto;
}
}
catch
{
return null;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.TacGias.Where(c => c.MaTacGia == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
public bool DeleteAuthor(int authorID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TacGia authorEnt = ent.TacGias.FirstOrDefault(c => c.TacGiaID == authorID);
authorEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckRelation(int authorID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.Saches.Where(s => s.MaTacGia == authorID).Count();
if (count > 0)
{
return true;
}
else
return false;
}
}
catch
{
return true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/AuthorDAO.cs | C# | asf20 | 6,172 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
namespace DAO
{
public class PayMoneyDAO
{
public int InsertPayMoney(PayMoneyDTO pmDto)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
PhieuThuTien pmInt = new PhieuThuTien
{
MaPhieuThu = pmDto.PayMoneyCode,
KhachHangID = pmDto.PayMoneyCustomerID,
SoTienThu = pmDto.Money,
NgayThu = (DateTime) pmDto.PayMoneyCreateDate,
NguoiLap = pmDto.PayMoneyUserID,
GhiChu = pmDto.PayMoneyNote,
SuDung = true
};
if (ent.PhieuThuTiens.Count(t => t.PhieuThuID != null) > 0)
{
pmInt.PhieuThuID = ent.PhieuThuTiens.Max(t => t.PhieuThuID) + 1;
}
else
{
pmInt.PhieuThuID = 1;
}
ent.AddToPhieuThuTiens(pmInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Payment.ToString());
ent.SaveChanges();
return pmInt.PhieuThuID;
}
}
public bool UpdatePayMoney(PayMoneyDTO payDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
PhieuThuTien payEnt = ent.PhieuThuTiens.FirstOrDefault(c => c.PhieuThuID == payDTO.PayMoneyID);
payEnt.GhiChu = payDTO.PayMoneyNote;
payEnt.SoTienThu = payEnt.SoTienThu + payDTO.Money;
payEnt.KhachHangID = payDTO.PayMoneyCustomerID;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public int GetTotalPay(int customerID, int month)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int year = DateTime.Now.Year;
List<PhieuThuTien> ptts = ent.PhieuThuTiens.Where(c => c.KhachHangID == customerID && DateTime.Parse(c.NgayThu.ToString()).Month == month && DateTime.Parse(c.NgayThu.ToString()).Year == year).ToList();
int total = 0;
foreach (PhieuThuTien pt in ptts)
{
total += (int)pt.SoTienThu;
}
return total;
}
}
catch
{
return 0;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/PayMoneyDAO.cs | C# | asf20 | 2,938 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class CategoryDAO
{
public CategoryDTO CreateCategoryDTOFromEntity(TheLoai theLoai)
{
CategoryDTO cateDto = new CategoryDTO {
CategoryCode = theLoai.MaTheLoai,
CategoryID = theLoai.TheLoaiID,
CategoryName = theLoai.TenTheLoai,
Status = bool.Parse( theLoai.SuDung.ToString())
};
return cateDto;
}
public int InsertCategory(CategoryDTO categoryDto)
{
using(BookStoreEntities ent = new BookStoreEntities())
{
TheLoai categoryInt = new TheLoai
{
MaTheLoai = categoryDto.CategoryCode,
TenTheLoai = categoryDto.CategoryName,
SuDung = true
};
if (ent.TheLoais.Count(t => t.TheLoaiID != null) > 0)
{
categoryInt.TheLoaiID = ent.TheLoais.Max(t => t.TheLoaiID) + 1;
}
else
{
categoryInt.TheLoaiID = 1;
}
ent.AddToTheLoais(categoryInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Category.ToString());
ent.SaveChanges();
return categoryInt.TheLoaiID;
}
}
public List<CategoryDTO> GetCategoryList()
{
List<CategoryDTO> listCategoryDto = new List<CategoryDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<TheLoai> listTheLoai = ent.TheLoais.Where(c => c.SuDung == true).ToList();
foreach (TheLoai item in listTheLoai)
{
CategoryDTO cateDto = CreateCategoryDTOFromEntity(item);
listCategoryDto.Add(cateDto);
}
}
return listCategoryDto;
}
public BindingList<CategoryDTO> GetNewBindingListCategory()
{
BindingList<CategoryDTO> listCategoryDto = new BindingList<CategoryDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<TheLoai> listTheLoai = ent.TheLoais.Where(c => c.SuDung == true).ToList();
foreach (TheLoai item in listTheLoai)
{
CategoryDTO cateDto = CreateCategoryDTOFromEntity(item);
listCategoryDto.Add(cateDto);
}
}
return listCategoryDto;
}
public bool UpdateCategory(CategoryDTO cateDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TheLoai cateEnt = ent.TheLoais.FirstOrDefault(c => c.TheLoaiID == cateDTO.CategoryID);
cateEnt.TenTheLoai = cateDTO.CategoryName;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public CategoryDTO GetCategoryByID(int cateID)
{
try
{
using(BookStoreEntities ent = new BookStoreEntities())
{
TheLoai cate = ent.TheLoais.FirstOrDefault(c => c.TheLoaiID == cateID);
CategoryDTO cateDTO = CreateCategoryDTOFromEntity(cate);
return cateDTO;
}
}
catch
{
return null;
}
}
public bool DeleteCategory(int cateID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
TheLoai cateEnt = ent.TheLoais.FirstOrDefault(c => c.TheLoaiID == cateID);
cateEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.TheLoais.Where(c => c.MaTheLoai == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/CategoryDAO.cs | C# | asf20 | 5,125 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class BookDAO
{
private BookDTO CreateBookDTOFromEntity(Sach s)
{
BookDTO bookDto = new BookDTO
{
AuthorID = int.Parse( s.MaTacGia.ToString()),
BookName = s.TenSach,
BookCode = s.MaSach,
ReceivePrice = float.Parse(s.GiaNhap.ToString()),
BookCost = float.Parse( s.DonGia.ToString()),
BookID = s.SachID,
CategoryID = int.Parse( s.MaTheLoai.ToString()),
StockQuantity = int.Parse( s.SoLuongTon.ToString())
};
return bookDto;
}
public BindingList<BookDTO> GetNewBindingList()
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
BindingList<BookDTO> listBook = new BindingList<BookDTO>();
foreach (Sach book in ent.Saches.Where(b => b.SuDung == true).ToList())
{
BookDTO bookDto = CreateBookDTOFromEntity(book);
bookDto.CategoryName = ent.TheLoais.FirstOrDefault(c => c.TheLoaiID == bookDto.CategoryID).TenTheLoai;
bookDto.AuthorName = ent.TacGias.FirstOrDefault(c => c.TacGiaID == bookDto.AuthorID).TenTacGia;
listBook.Add(bookDto);
}
return listBook;
}
}
catch
{
return null;
}
}
public int InsertBook(BookDTO bookDto)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
Sach bookEnt = new Sach
{
MaSach = bookDto.BookCode,
TenSach = bookDto.BookName,
MaTheLoai = bookDto.CategoryID,
MaTacGia = bookDto.AuthorID,
SoLuongTon = 0,
SuDung = true,
DonGia = bookDto.BookCost,
GiaNhap = bookDto.ReceivePrice
};
if (ent.Saches.Count(t => t.SachID != null) > 0)
{
bookEnt.SachID = ent.Saches.Max(t => t.SachID) + 1;
}
else
{
bookEnt.SachID = 1;
}
ent.AddToSaches(bookEnt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Book.ToString());
ent.SaveChanges();
return bookEnt.SachID;
}
}
catch
{
return -1;
}
}
public bool UpdateBook(BookDTO bookDto)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
Sach bookEnt = ent.Saches.FirstOrDefault(c => c.SachID == bookDto.BookID);
bookEnt.TenSach = bookDto.BookName;
bookEnt.MaTacGia = bookDto.AuthorID;
bookEnt.MaTheLoai = bookDto.CategoryID;
bookEnt.DonGia = bookDto.BookCost;
bookEnt.GiaNhap = bookDto.ReceivePrice;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool UpdateQuantityFromReceiving(int id, int quantity)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
Sach sach = ent.Saches.FirstOrDefault(s => s.SachID == id);
sach.SoLuongTon += quantity;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public BookDTO GetBookByID(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
Sach bookEnt = ent.Saches.FirstOrDefault(c => c.SachID == ID);
BookDTO bookDto = CreateBookDTOFromEntity(bookEnt);
bookDto.CategoryName = ent.TheLoais.FirstOrDefault(c => c.TheLoaiID == bookDto.CategoryID).TenTheLoai;
bookDto.AuthorName = ent.TacGias.FirstOrDefault(a => a.TacGiaID == bookDto.AuthorID).TenTacGia;
return bookDto;
}
}
catch
{
return null;
}
}
public bool DeleteBook(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
Sach bookEnt = ent.Saches.FirstOrDefault(c => c.SachID == ID);
bookEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.Saches.Where(c => c.MaSach == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
public List<BookReportDTO> GetListBookForReport(DateTime from, DateTime to)
{
List<BookReportDTO> listReport = new List<BookReportDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<Sach> listBook = ent.Saches.Where(s => s.SuDung == true).ToList();
ReceivingDAO receiDAO =new ReceivingDAO();
InvoiceDAO invoiceDAO = new InvoiceDAO();
foreach (Sach s in listBook)
{
BookReportDTO bookRpt = new BookReportDTO();
bookRpt.BookID = s.SachID;
bookRpt.BookName = s.TenSach;
bookRpt.AuthorName = ent.TacGias.First(t => t.TacGiaID == s.MaTacGia).TenTacGia;
bookRpt.CategoryName = ent.TheLoais.First(t => t.TheLoaiID == s.MaTheLoai).TenTheLoai;
bookRpt.StockQuantity = s.SoLuongTon ?? 0;
bookRpt.ReceiveQuantity = receiDAO.GetReceivingQuantity(s.SachID, from, to);
bookRpt.SellQuantity = invoiceDAO.GetQuantitySellForReport(s.SachID, from, to);
listReport.Add(bookRpt);
}
}
return listReport;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/BookDAO.cs | C# | asf20 | 7,672 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class UsersGroupDAO
{
public UsersGroupDTO GetUsersGroupByID(int userGroupID)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
LoaiNhanVien type = ent.LoaiNhanViens.FirstOrDefault(t => t.LoaiNhanVienID == userGroupID && t.LoaiNhanVienID != null);
UsersGroupDTO userGroup = new UsersGroupDTO
{
UsersGroupID = type.LoaiNhanVienID,
UsersGroupCode = type.MaLoaiNhanVien,
UsersGroupName = type.TenLoaiNhanVien,
Status = bool.Parse( type.SuDung.ToString())
};
return userGroup;
}
}
public UsersGroupDTO CreateUsersGroupDTOFromEntity(LoaiNhanVien loaiNhanVien)
{
UsersGroupDTO UserDto = new UsersGroupDTO
{
UsersGroupCode = loaiNhanVien.MaLoaiNhanVien,
UsersGroupID = loaiNhanVien.LoaiNhanVienID,
UsersGroupName = loaiNhanVien.TenLoaiNhanVien,
Status = bool.Parse(loaiNhanVien.SuDung.ToString())
};
return UserDto;
}
public int InsertUsersGroup(UsersGroupDTO userGroup)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
LoaiNhanVien type = new LoaiNhanVien
{
MaLoaiNhanVien = userGroup.UsersGroupCode,
TenLoaiNhanVien = userGroup.UsersGroupName,
SuDung = userGroup.Status
};
if (ent.LoaiNhanViens.Count(t => t.LoaiNhanVienID != null) > 0)
{
type.LoaiNhanVienID = ent.LoaiNhanViens.Max(t => t.LoaiNhanVienID) + 1;
}
else
{
type.LoaiNhanVienID = 1;
}
ent.AddToLoaiNhanViens(type);
ent.SaveChanges();
return type.LoaiNhanVienID;
}
}
catch (Exception ex)
{
return -1;
}
}
public List<UsersGroupDTO> GetUsersGroupList()
{
List<UsersGroupDTO> listUsersGroupDto = new List<UsersGroupDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<LoaiNhanVien> listLoaiNhanVien = ent.LoaiNhanViens.Where(c => c.SuDung == true).ToList();
foreach (LoaiNhanVien item in listLoaiNhanVien)
{
UsersGroupDTO UserDto = CreateUsersGroupDTOFromEntity(item);
listUsersGroupDto.Add(UserDto);
}
}
return listUsersGroupDto;
}
public BindingList<UsersGroupDTO> GetNewBindingListUsersGroup()
{
BindingList<UsersGroupDTO> listUsersGroupDto = new BindingList<UsersGroupDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<LoaiNhanVien> listLoaiNhanVien = ent.LoaiNhanViens.Where(c => c.SuDung == true).ToList();
foreach (LoaiNhanVien item in listLoaiNhanVien)
{
UsersGroupDTO UserDto = CreateUsersGroupDTOFromEntity(item);
listUsersGroupDto.Add(UserDto);
}
}
return listUsersGroupDto;
}
public bool UpdateUsersGroup(UsersGroupDTO userDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
LoaiNhanVien userEnt = ent.LoaiNhanViens.FirstOrDefault(c => c.LoaiNhanVienID == userDTO.UsersGroupID);
userEnt.TenLoaiNhanVien = userDTO.UsersGroupName;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public UsersGroupDTO GetCategoryByID(int userID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
LoaiNhanVien cate = ent.LoaiNhanViens.FirstOrDefault(c => c.LoaiNhanVienID == userID);
UsersGroupDTO userDTO = CreateUsersGroupDTOFromEntity(cate);
return userDTO;
}
}
catch
{
return null;
}
}
public bool DeleteUsersGroup(int userID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
LoaiNhanVien userEnt = ent.LoaiNhanViens.FirstOrDefault(c => c.LoaiNhanVienID == userID);
userEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.LoaiNhanViens.Where(c => c.MaLoaiNhanVien == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/UsersGroupDAO.cs | C# | asf20 | 6,177 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DAO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DAO")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("275ba679-00b8-4e01-8c90-105a6ad660db")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/Properties/AssemblyInfo.cs | C# | asf20 | 1,418 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class ParameterDAO
{
private ParameterDTO CreateParameterDTOFromEntity(ThamSo ts)
{
ParameterDTO paraDto = new ParameterDTO
{
ParameterID = ts.ThamSoID,
ParameterCode = ts.MaThamSo,
ParameterName = ts.TenThamSo,
Value = int.Parse(ts.GiaTri.ToString()),
Status = bool.Parse( ts.SuDung.ToString())
};
return paraDto;
}
public int GetParameterValueByCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ThamSo para = ent.ThamSoes.FirstOrDefault(p => p.MaThamSo == code);
return para != null ? int.Parse(para.GiaTri.ToString()) : -1;
}
}
catch
{
return -1;
}
}
public ParameterDTO GetParameterByID(int id)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ThamSo ts = ent.ThamSoes.FirstOrDefault(p => p.ThamSoID == id);
return CreateParameterDTOFromEntity(ts);
}
}
catch
{
return null;
}
}
public int InsertParameter(ParameterDTO paramDto)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ThamSo paramInt = new ThamSo
{
MaThamSo = paramDto.ParameterCode,
TenThamSo = paramDto.ParameterName,
GiaTri = paramDto.Value,
SuDung = true
};
if (ent.ThamSoes.Count(t => t.ThamSoID != null) > 0)
{
paramInt.ThamSoID = ent.ThamSoes.Max(t => t.ThamSoID) + 1;
}
else
{
paramInt.ThamSoID = 1;
}
ent.AddToThamSoes(paramInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Parameter.ToString());
ent.SaveChanges();
return paramInt.ThamSoID;
}
}
public List<ParameterDTO> GetParameterList()
{
List<ParameterDTO> listParameterDto = new List<ParameterDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<ThamSo> listThamSo = ent.ThamSoes.ToList();
foreach (ThamSo item in listThamSo)
{
ParameterDTO paramDto = CreateParameterDTOFromEntity(item);
listParameterDto.Add(paramDto);
}
}
return listParameterDto;
}
public BindingList<ParameterDTO> GetNewBindingListParameter()
{
BindingList<ParameterDTO> listParameterDto = new BindingList<ParameterDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<ThamSo> listThamSo = ent.ThamSoes.ToList();
foreach (ThamSo item in listThamSo)
{
ParameterDTO paramDto = CreateParameterDTOFromEntity(item);
listParameterDto.Add(paramDto);
}
}
return listParameterDto;
}
public bool UpdateParameter(ParameterDTO paramDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ThamSo paramEnt = ent.ThamSoes.FirstOrDefault(c => c.ThamSoID == paramDTO.ParameterID);
paramEnt.TenThamSo = paramDTO.ParameterName;
paramEnt.GiaTri = paramDTO.Value;
paramEnt.SuDung = paramDTO.Status;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool DeleteParameter(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
ThamSo paramEnt = ent.ThamSoes.FirstOrDefault(c => c.ThamSoID == ID);
paramEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.ThamSoes.Where(c => c.MaThamSo == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/ParameterDAO.cs | C# | asf20 | 5,688 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class CustomerDAO
{
public CustomerDTO CreateCustomerDTOFromEntity(KhachHang khachHang)
{
CustomerDTO cusDto = new CustomerDTO
{
CustomerCode = khachHang.MaKhachHang,
CustomerID = khachHang.KhachHangID,
CustomerName = khachHang.HoTen,
CustomerCMND = khachHang.CMND,
CustomerPhone = khachHang.DienThoai ?? string.Empty,
CustomerBirthday = (DateTime)khachHang.NgaySinh,
CustomerAddress = khachHang.DiaChi ?? string.Empty,
CustomerEmail = khachHang.Email ?? string.Empty,
CustomerSex = (bool) khachHang.GioiTinh,
CustomerBeginDay = (DateTime)khachHang.NgayThem,
CustomerDebtMoney =(float) khachHang.TienNo,
Note = khachHang.GhiChu ?? string.Empty,
Status = bool.Parse(khachHang.SuDung.ToString())
};
return cusDto;
}
public int InsertCustomer(CustomerDTO cusDto)
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang cusInt = new KhachHang
{
MaKhachHang = cusDto.CustomerCode,
HoTen = cusDto.CustomerName,
NgaySinh = cusDto.CustomerBirthday,
DiaChi = cusDto.CustomerAddress,
DienThoai = cusDto.CustomerPhone,
Email = cusDto.CustomerEmail,
GioiTinh = cusDto.CustomerSex,
CMND = cusDto.CustomerCMND,
NgayThem = cusDto.CustomerBeginDay,
TienNo = cusDto.CustomerDebtMoney,
GhiChu = cusDto.Note,
SuDung = true
};
if (ent.KhachHangs.Count(t => t.KhachHangID != null) > 0)
{
cusInt.KhachHangID = ent.KhachHangs.Max(t => t.KhachHangID) + 1;
}
else
{
cusInt.KhachHangID = 1;
}
ent.AddToKhachHangs(cusInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Customer.ToString());
ent.SaveChanges();
return cusInt.KhachHangID;
}
}
public List<CustomerDTO> GetCustomerList()
{
List<CustomerDTO> listCustomerDto = new List<CustomerDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<KhachHang> listKhachHang = ent.KhachHangs.Where(c => c.SuDung == true).ToList();
foreach (KhachHang item in listKhachHang)
{
CustomerDTO cusDto = CreateCustomerDTOFromEntity(item);
listCustomerDto.Add(cusDto);
}
}
return listCustomerDto;
}
public BindingList<CustomerDTO> GetNewBindingListCustomer()
{
BindingList<CustomerDTO> listCustomerDto = new BindingList<CustomerDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<KhachHang> listKhachHang = ent.KhachHangs.Where(c => c.SuDung == true).ToList();
foreach (KhachHang item in listKhachHang)
{
CustomerDTO cusDto = CreateCustomerDTOFromEntity(item);
if (cusDto.CustomerSex)
cusDto.CustomerSexString = "Nam";
else
cusDto.CustomerSexString = "Nữ";
listCustomerDto.Add(cusDto);
}
}
return listCustomerDto;
}
public bool UpdateCustomer(CustomerDTO cusDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang cusEnt = ent.KhachHangs.FirstOrDefault(c => c.KhachHangID == cusDTO.CustomerID);
cusEnt.HoTen = cusDTO.CustomerName;
cusEnt.NgaySinh = cusDTO.CustomerBirthday;
cusEnt.DiaChi = cusDTO.CustomerAddress;
cusEnt.DienThoai = cusDTO.CustomerPhone;
cusEnt.Email = cusDTO.CustomerEmail;
cusEnt.GioiTinh = cusDTO.CustomerSex;
cusEnt.CMND = cusDTO.CustomerCMND;
cusEnt.GhiChu = cusDTO.Note;
cusEnt.SuDung = cusDTO.Status;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool UpdateCustomerDebtMoney(int cusID, double debtMoney)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang cusEnt = ent.KhachHangs.FirstOrDefault(c => c.KhachHangID == cusID);
cusEnt.TienNo = debtMoney;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool UpdateCustomerDebtFromInvoice(int ID, float total)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang cusEnt = ent.KhachHangs.FirstOrDefault(c => c.KhachHangID == ID);
cusEnt.TienNo += total;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public CustomerDTO GetCustomerByID(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang customer = ent.KhachHangs.FirstOrDefault(c => c.KhachHangID == ID);
CustomerDTO cusDTO = CreateCustomerDTOFromEntity(customer);
if (cusDTO.CustomerSex)
cusDTO.CustomerSexString = "Nam";
else
cusDTO.CustomerSexString = "Nữ";
return cusDTO;
}
}
catch
{
return null;
}
}
public bool DeleteCustomer(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang cusEnt = ent.KhachHangs.FirstOrDefault(c => c.KhachHangID == ID);
cusEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.KhachHangs.Where(c => c.MaKhachHang == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
public CustomerDTO GetCustomerByCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
KhachHang kh = ent.KhachHangs.FirstOrDefault(k => k.MaKhachHang == code);
return CreateCustomerDTOFromEntity(kh);
}
}
catch
{
return null;
}
}
public List<CustomerReportDTO> GetListCustomerForReport(int month)
{
List<CustomerReportDTO> listReport = new List<CustomerReportDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<KhachHang> listCustomer = ent.KhachHangs.Where(kh => kh.SuDung == true).ToList();
PayMoneyDAO payDAO = new PayMoneyDAO();
InvoiceDAO invoiceDAO = new InvoiceDAO();
foreach (KhachHang kh in listCustomer)
{
CustomerReportDTO CusRpt = new CustomerReportDTO();
CusRpt.CustomerID = kh.KhachHangID;
CusRpt.CustomerCode = kh.MaKhachHang;
CusRpt.CustomerName = kh.HoTen;
CusRpt.CustomerAddress = kh.DiaChi;
CusRpt.CustomerCMND = kh.CMND;
CusRpt.CustomerPhone = kh.DienThoai;
DateTime now = DateTime.Now;
//neu la thang hien tai
if (month == now.Month)
{
CusRpt.EndDebt = (int)kh.TienNo;
}
else
{
int totalPay = 0;
int totalBuy = 0;
for (int m = month + 1; m <= month; m++)
{
totalPay += payDAO.GetTotalPay(kh.KhachHangID, m);
totalBuy += invoiceDAO.GetTotalBuy(kh.KhachHangID, m);
}
CusRpt.EndDebt = (int)kh.TienNo - (totalBuy - totalPay);
}
CusRpt.TotalPay = payDAO.GetTotalPay(kh.KhachHangID, month);
CusRpt.TotalBuy = invoiceDAO.GetTotalBuy(kh.KhachHangID, month);
CusRpt.FirstDebt = (CusRpt.TotalPay - CusRpt.TotalBuy) + CusRpt.EndDebt;
listReport.Add(CusRpt);
}
}
return listReport;
}
public List<CustomerReportDTO> GetListCustomerForReport(int customerID, int month)
{
List<CustomerReportDTO> listReport = new List<CustomerReportDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<KhachHang> listCustomer = ent.KhachHangs.Where(kh => kh.SuDung == true && kh.KhachHangID == customerID).ToList();
PayMoneyDAO payDAO = new PayMoneyDAO();
InvoiceDAO invoiceDAO = new InvoiceDAO();
foreach (KhachHang kh in listCustomer)
{
CustomerReportDTO CusRpt = new CustomerReportDTO();
CusRpt.CustomerID = kh.KhachHangID;
CusRpt.CustomerCode = kh.MaKhachHang;
CusRpt.CustomerName = kh.HoTen;
CusRpt.CustomerAddress = kh.DiaChi;
CusRpt.CustomerCMND = kh.CMND;
CusRpt.CustomerPhone = kh.DienThoai;
DateTime now = DateTime.Now;
//neu la thang hien tai
if (month == now.Month)
{
CusRpt.EndDebt = (int)kh.TienNo;
}
else
{
int totalPay = 0;
int totalBuy = 0;
for (int m = month + 1; m <= month; m++)
{
totalPay += payDAO.GetTotalPay(kh.KhachHangID, m);
totalBuy += invoiceDAO.GetTotalBuy(kh.KhachHangID, m);
}
CusRpt.EndDebt = (int)kh.TienNo - (totalBuy - totalPay);
}
CusRpt.TotalPay = payDAO.GetTotalPay(kh.KhachHangID, month);
CusRpt.TotalBuy = invoiceDAO.GetTotalBuy(kh.KhachHangID, month);
CusRpt.FirstDebt = (CusRpt.TotalPay - CusRpt.TotalBuy) + CusRpt.EndDebt;
listReport.Add(CusRpt);
}
}
return listReport;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/CustomerDAO.cs | C# | asf20 | 12,910 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class EmployeeDAO
{
public EmployeeDTO CreateEmployeeDTOFromEntity(NhanVien nhanVien)
{
EmployeeDTO EmpDto = new EmployeeDTO
{
EmployeeID = nhanVien.NhanVienID,
EmployeeCode = nhanVien.MaNhanVien ?? string.Empty,
EmployeeName = nhanVien.HoTen ?? string.Empty,
EmployeeBirthDay = (DateTime)nhanVien.NgaySinh,
EmployeeEmail = nhanVien.Email ?? string.Empty,
EmployeePhone = nhanVien.DienThoai ?? string.Empty,
EmployeeCMND = nhanVien.CMND ?? string.Empty,
EmployeeSex = bool.Parse(nhanVien.GioiTinh.ToString()),
EmployeeSexName = bool.Parse(nhanVien.GioiTinh.ToString())?"Nam" : "Nữ" ,
EmployeeAddress = nhanVien.DiaChi ?? string.Empty,
EmployeeBeginDay = nhanVien.NgayThem.HasValue ? nhanVien.NgaySinh.Value : DateTime.Now,
EmployeeKindCode = (int)nhanVien.MaLoaiNV,
EmployeeNote = nhanVien.GhiChu ?? string.Empty,
EmployeeStatus = bool.Parse(nhanVien.SuDung.ToString())
};
return EmpDto;
}
public int InsertEmployee(EmployeeDTO employeeDto)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NhanVien nhanVienInt = new NhanVien
{
MaNhanVien = employeeDto.EmployeeCode,
HoTen = employeeDto.EmployeeName,
NgaySinh = employeeDto.EmployeeBirthDay,
Email = employeeDto.EmployeeEmail,
DienThoai = employeeDto.EmployeePhone,
CMND = employeeDto.EmployeeCMND,
GioiTinh = employeeDto.EmployeeSex,
DiaChi = employeeDto.EmployeeAddress,
NgayThem = employeeDto.EmployeeBeginDay,
MaLoaiNV = employeeDto.EmployeeKindCode,
GhiChu = employeeDto.EmployeeNote,
SuDung = true
};
if (ent.NhanViens.Count(t => t.NhanVienID != null) > 0)
{
nhanVienInt.NhanVienID = ent.NhanViens.Max(t => t.NhanVienID) + 1;
}
else
{
nhanVienInt.NhanVienID = 1;
}
ent.AddToNhanViens(nhanVienInt);
DocSequenceDAO docSeqDAO = new DocSequenceDAO();
docSeqDAO.UpdateNextDocSequence(DocSequence.Employee.ToString());
ent.SaveChanges();
return nhanVienInt.NhanVienID;
}
}
catch
{
return -1;
}
}
public List<EmployeeDTO> GetEmployeeList()
{
List<EmployeeDTO> listEmployeeDto = new List<EmployeeDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<NhanVien> listNhanVien = ent.NhanViens.Where(c => c.SuDung == true).ToList();
foreach (NhanVien item in listNhanVien)
{
EmployeeDTO empDto = CreateEmployeeDTOFromEntity(item);
listEmployeeDto.Add(empDto);
}
}
return listEmployeeDto;
}
public BindingList<EmployeeDTO> GetNewBindingListEmployee()
{
BindingList<EmployeeDTO> listEmployeeDto = new BindingList<EmployeeDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<NhanVien> listNhanVien = ent.NhanViens.Where(c => c.SuDung == true).ToList();
foreach (NhanVien item in listNhanVien)
{
EmployeeDTO EmpDto = CreateEmployeeDTOFromEntity(item);
listEmployeeDto.Add(EmpDto);
}
}
return listEmployeeDto;
}
public bool UpdateEmployee(EmployeeDTO EmpDTO)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NhanVien EmpEnt = ent.NhanViens.FirstOrDefault(c => c.NhanVienID == EmpDTO.EmployeeID);
EmpEnt.HoTen = EmpDTO.EmployeeName;
EmpEnt.NgaySinh = EmpDTO.EmployeeBirthDay;
EmpEnt.Email = EmpDTO.EmployeeEmail;
EmpEnt.DienThoai = EmpDTO.EmployeePhone;
EmpEnt.CMND = EmpDTO.EmployeeCMND;
EmpEnt.GioiTinh = EmpDTO.EmployeeSex;
EmpEnt.DiaChi = EmpDTO.EmployeeAddress;
EmpEnt.NgayThem = EmpDTO.EmployeeBeginDay;
EmpEnt.MaLoaiNV = EmpDTO.EmployeeKindCode;
EmpEnt.SuDung = EmpDTO.EmployeeStatus;
EmpEnt.GhiChu = EmpDTO.EmployeeNote;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public EmployeeDTO GetEmployeeByID(int EmpID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NhanVien emp = ent.NhanViens.FirstOrDefault(c => c.NhanVienID == EmpID);
EmployeeDTO EmpDTO = CreateEmployeeDTOFromEntity(emp);
return EmpDTO;
}
}
catch
{
return null;
}
}
public bool DeleteEmployee(int empID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NhanVien EmpEnt = ent.NhanViens.FirstOrDefault(c => c.NhanVienID == empID);
EmpEnt.SuDung = false;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckExistsCode(string code)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
int count = ent.NhanViens.Where(c => c.MaNhanVien == code).Count();
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return true;
}
}
public List<UsersGroupDTO> Load_UserGroup()
{
List<UsersGroupDTO> listUsersGroupDto = new List<UsersGroupDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<LoaiNhanVien> listLoaiNhanVien = ent.LoaiNhanViens.Where(c => c.SuDung == true).ToList();
foreach (LoaiNhanVien item in listLoaiNhanVien)
{
UsersGroupDTO USGDto = new UsersGroupDTO
{
UsersGroupID = item.LoaiNhanVienID,
UsersGroupCode = item.MaLoaiNhanVien,
UsersGroupName = item.TenLoaiNhanVien,
Status = (bool)item.SuDung
};
listUsersGroupDto.Add(USGDto);
}
}
return listUsersGroupDto;
}
public List<EmployeeDTO> GetEmployeeNotHasAccount()
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
List<EmployeeDTO> ListEmployee = new List<EmployeeDTO>();
List<NhanVien> listEmp = ent.NhanViens.ToList();
List<NguoiDung> listAcc = ent.NguoiDungs.ToList();
foreach (NhanVien nv in listEmp)
{
if (!listAcc.Exists(n => n.NhanVienID == nv.NhanVienID))
{
ListEmployee.Add(CreateEmployeeDTOFromEntity(nv));
}
}
return ListEmployee;
}
}
catch
{
return null;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/EmployeeDAO.cs | C# | asf20 | 9,121 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.ComponentModel;
namespace DAO
{
public class AccountDAO
{
public AccountDTO CreateAccountDTOFromEntity(NguoiDung nd)
{
try
{
AccountDTO Acc = new AccountDTO
{
EmployeeID = nd.NhanVienID,
Password = nd.MatKhau ?? string.Empty,
UserName = nd.TaiKhoan ?? string.Empty
};
if (nd.NhanVienID > 0)
{
EmployeeDAO empDAO = new EmployeeDAO();
EmployeeDTO empDTO = empDAO.GetEmployeeByID(nd.NhanVienID);
Acc.EmployeeName = empDTO.EmployeeName;
Acc.EmPloyeeCard = empDTO.EmployeeCMND;
}
return Acc;
}
catch
{
return null;
}
}
public int InsertAccount(AccountDTO Acc)
{
try
{
using( BookStoreEntities ent = new BookStoreEntities())
{
NguoiDung nd = new NguoiDung
{
NhanVienID = Acc.EmployeeID,
TaiKhoan = Acc.UserName,
MatKhau =Acc.Password
};
if (ent.NguoiDungs.Where(n => n.TaiKhoan == nd.TaiKhoan).Count() > 0)
{
return -1;
}
else if (ent.NguoiDungs.Where(n => n.NhanVienID == nd.NhanVienID).Count() > 0)
{
return -1;
}
ent.AddToNguoiDungs(nd);
ent.SaveChanges();
return Acc.EmployeeID;
}
}
catch
{
return 0;
}
}
public bool UpdateAccount(AccountDTO Acc)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NguoiDung nd = ent.NguoiDungs.FirstOrDefault(n => n.NhanVienID == Acc.EmployeeID);
nd.MatKhau = Acc.Password;
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool DeleteAccount(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
NguoiDung nd = ent.NguoiDungs.FirstOrDefault(n => n.NhanVienID == ID);
ent.NguoiDungs.DeleteObject(nd);
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public BindingList<AccountDTO> GetNewBindingList()
{
try
{
BindingList<AccountDTO> ListAcc = new BindingList<AccountDTO>();
using (BookStoreEntities ent = new BookStoreEntities())
{
List<NguoiDung> listND = new List<NguoiDung>();
listND = ent.NguoiDungs.ToList();
foreach (NguoiDung nd in listND)
{
ListAcc.Add(CreateAccountDTOFromEntity(nd));
}
}
return ListAcc;
}
catch
{
return null;
}
}
public AccountDTO GetAccountByID(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
AccountDTO Acc = new AccountDTO();
NguoiDung nd = ent.NguoiDungs.FirstOrDefault(n => n.NhanVienID == ID);
Acc = CreateAccountDTOFromEntity(nd);
return Acc;
}
}
catch
{
return null;
}
}
public bool Login(string userName, string password, out AccountDTO acc)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
acc = new AccountDTO();
if (ent.NguoiDungs.Where(n => n.TaiKhoan == userName && n.MatKhau == password).Count() > 0)
{
NguoiDung nd = ent.NguoiDungs.FirstOrDefault(n => n.TaiKhoan == userName && n.MatKhau == password);
acc = CreateAccountDTOFromEntity(nd);
return true;
}
else
{
acc = null;
return false;
}
}
}
catch
{
acc = null;
return false;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/AccountDAO.cs | C# | asf20 | 5,413 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
namespace DAO
{
public class RuleObjectDAO
{
private RuleObjectDTO CreateRuleObjectDTOFromEntity(PhanQuyen pq)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
RuleObjectDTO rule = new RuleObjectDTO
{
GroupID = pq.LoaiNhanVienID,
RuleID = pq.QuyenID,
Status = pq.TinhTrang.HasValue ? pq.TinhTrang.Value : false
};
rule.RuleName = ent.Quyens.FirstOrDefault(r => r.QuyenID == rule.RuleID).TenQuyen;
return rule;
}
}
catch
{
return null;
}
}
public bool InsertRuleOfGroup(int ID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
List<Quyen> listRule = ent.Quyens.ToList();
foreach (Quyen q in listRule)
{
PhanQuyen pq = new PhanQuyen
{
QuyenID = q.QuyenID,
LoaiNhanVienID = ID,TinhTrang = false
};
switch (q.QuyenID)
{
case (int)RuleObject.SellBook:
case (int)RuleObject.PayDebt:
case (int)RuleObject.Receiving:
case (int)RuleObject.BookList:
case (int)RuleObject.AuthorList:
case (int)RuleObject.CategoryList:
case (int)RuleObject.CustomerList:
case (int)RuleObject.EmployeeList:
pq.TinhTrang = true;
break;
}
ent.AddToPhanQuyens(pq);
}
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool CheckPermission(int groupID, int RuleID)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
return ent.PhanQuyens.FirstOrDefault(r => r.LoaiNhanVienID == groupID && r.QuyenID == RuleID).TinhTrang.Value;
}
}
catch
{
return false;
}
}
public List<RuleObjectDTO> GetListRuleObject(int id)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
List<PhanQuyen> listPQ = ent.PhanQuyens.Where(p => p.LoaiNhanVienID == id).ToList();
List<RuleObjectDTO> listRule = new List<RuleObjectDTO>();
foreach (PhanQuyen pq in listPQ)
{
listRule.Add(CreateRuleObjectDTOFromEntity(pq));
}
return listRule;
}
}
catch
{
return null;
}
}
public bool UpdateRuleObject(List<RuleObjectDTO> listRule)
{
try
{
using (BookStoreEntities ent = new BookStoreEntities())
{
foreach (RuleObjectDTO rule in listRule)
{
PhanQuyen pq = ent.PhanQuyens.FirstOrDefault(p => p.LoaiNhanVienID == rule.GroupID && p.QuyenID == rule.RuleID);
pq.TinhTrang = rule.Status;
}
ent.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DAO/RuleObjectDAO.cs | C# | asf20 | 4,344 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class UsersGroupDTO
{
public int UsersGroupID { get; set; }
public string UsersGroupName { get; set; }
public string UsersGroupCode { get; set; }
public bool Status { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/UsersGroupDTO.cs | C# | asf20 | 361 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class AuthorDTO
{
public int AuthorID { get; set; }
public string AuthorCode { get; set; }
public string AuthorName { get; set; }
public bool Status { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/AuthorDTO.cs | C# | asf20 | 345 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class ReceivingListDTO
{
public int ReceivingID { get; set; }
public string ReceivingCode { get; set; }
public DateTime ReceivingDate { get; set; }
public float GrandTotal { get; set; }
public int CreatedBy { get; set; }
public bool Status { get; set; }
public string Description { get; set; }
public string CreatorName { get; set; }
public List<ReceivingDetailDTO> ListReceiving;
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/ReceivingListDTO.cs | C# | asf20 | 618 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class EmployeeDTO
{
public int EmployeeID { get; set; }
public String EmployeeCode { get; set; }
public String EmployeeName { get; set; }
public DateTime EmployeeBirthDay { get; set; }
public String EmployeeEmail { get; set; }
public String EmployeePhone { get; set; }
public String EmployeeCMND { get; set; }
public bool EmployeeSex { get; set; }
public String EmployeeSexName { get; set; }
public String EmployeeAddress { get; set; }
public DateTime EmployeeBeginDay { get; set; }
public int EmployeeKindCode { get; set; }
public bool EmployeeStatus { get; set; }
public String EmployeeNote { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/EmployeeDTO.cs | C# | asf20 | 872 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class ReceivingDetailDTO
{
public int ReceivingDetailID { get; set; }
public int ReceivingID { get; set; }
public int BookID { get; set; }
public int Quantity { get; set; }
public float UnitPrice { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/ReceivingDetailDTO.cs | C# | asf20 | 403 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class InvoiceDTO
{
public int InvoiceID { get; set; }
public string InvoiceCode { get; set; }
public int CustomerID { get; set; }
public DateTime CreatedDate { get; set; }
public float GrandTotal { get; set; }
public int CreatedBy { get; set; }
public string Description { get; set; }
public bool Status { get; set; }
public string CustomerName { get; set; }
public List<InvoiceDetailDTO> ListInvoiceDetail { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/InvoiceDTO.cs | C# | asf20 | 669 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class AccountDTO
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string EmPloyeeCard { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/AccountDTO.cs | C# | asf20 | 396 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class RuleObjectDTO
{
public int RuleID { get; set; }
public string RuleName { get; set; }
public bool Status { get; set; }
public int GroupID { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/RuleObjectDTO.cs | C# | asf20 | 333 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class CategoryDTO
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string CategoryCode { get; set; }
public bool Status { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/CategoryDTO.cs | C# | asf20 | 347 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class BookDTO
{
public int BookID { get; set; }
public string BookCode { get; set; }
public int CategoryID { get; set; }
public int AuthorID { get; set; }
public int StockQuantity { get; set; }
public float BookCost { get; set; }
public string BookName { get; set; }
public string CategoryName { get; set; }
public string AuthorName { get; set; }
public float ReceivePrice { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/BookDTO.cs | C# | asf20 | 635 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class CustomerReportDTO
{
public int CustomerID { get; set; }
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerCMND { get; set; }
public string CustomerPhone { get; set; }
public int FirstDebt { get; set; }
public int TotalBuy { get; set; }
public int TotalPay { get; set; }
public int EndDebt { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/CustomerReportDTO.cs | C# | asf20 | 655 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
class EnumCollection
{
}
public enum RuleObject
{
SellBook = 1,
PayDebt = 2,
Receiving = 3,
BookList = 4,
ActionBook = 5,
AuthorList = 6,
ActionAuthor = 7,
CategoryList = 8,
ActionCategory = 9,
CustomerList = 10,
ActionCustomer = 11,
EmployeeList = 12,
ActionEmployee = 13,
UserGroup = 14,
ActionUserGroup = 15,
AccountList = 16,
ActionAccount = 17,
StockReport = 18,
DebtReport = 19,
Param = 20,
DocSequence = 21,
RuleObject = 23
}
public enum EmployeeColumn
{
EmployeeID,EmployeeCode,EmployeeName
}
public enum Author
{
AuthorName,
AuthorCode,
AuthorID
}
public enum Category
{
CategoryName,
CategoryCode,
CategoryID
}
public enum BookColumn
{
BookName, BookID, BookCode
}
public enum ParameterCode
{
MinReceiving, MaxReceiving, MaxDebt, MinAge, MinAfterSell
}
public enum RibbonTabItemIndex
{
indexRbTabItem = 1,
mainMenuRbTabItem = 2,
bookRbTabItem = 3,
CustomerRbTabItem = 4,
EmployeeRbTabItem =5,
ReportRbTabItem = 6,
settingRbTabItem = 7
}
public enum DocSequence
{
Employee,
Invoice,
Customer,
Receiving,
Payment,
Book,
Author,
Category,
Parameter
}
public enum ActionName
{
Delete,
Insert,
Update,
View
}
public enum UserGroup
{
UsersGroupID,
UsersGroupName,
UsersGroupCode,
Status
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/EnumCollection.cs | C# | asf20 | 2,000 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace DTO
{
public static class Utility
{
public static void LogEx(Exception ex)
{
StreamWriter file = new StreamWriter(Application.StartupPath + @"\log.txt", true);
string lines = ex.TargetSite.ToString();
file.WriteLine("Target Site:");
file.WriteLine(" " + lines);
lines = ex.StackTrace.ToString();
file.WriteLine("Stack Trace:");
file.WriteLine(" " + lines);
lines = ex.Source;
file.WriteLine("Source:");
file.WriteLine(" " + lines);
lines = ex.Message;
file.WriteLine("Message:");
file.WriteLine(" " + lines);
file.WriteLine();
file.WriteLine("======= ========= ========= ======= ======== ======= ========= ======");
//lines = ex.InnerException.ToString();
//file.Write(lines);
//lines = ex.HelpLink;
//file.Write(lines);
//lines = ex.Data.ToString();
//file.Write(lines);
file.Close();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/Utility.cs | C# | asf20 | 1,307 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class DocSequenceDTO
{
public int DocSequenceID { get; set; }
public string DocSequenceName { get; set; }
public int NumLength { get; set; }
public int CurrentNum { get; set; }
public string DocSequenceCode { get; set; }
public string Separator { get; set; }
public string Middle { get; set; }
public string DocSequenceText { get; set; }
public string DocSequenceTemp { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/DocSequenceDTO.cs | C# | asf20 | 619 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class CustomerDTO
{
public int CustomerID { get; set; }
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
public string CustomerCMND { get; set; }
public string CustomerPhone { get; set; }
public DateTime CustomerBirthday{ get; set; }
public string CustomerAddress { get; set; }
public string CustomerEmail { get; set; }
public bool CustomerSex { get; set; }
public string CustomerSexString { get;set; }
public DateTime CustomerBeginDay { get; set; }
public float CustomerDebtMoney { get; set; }
public bool Status { get; set; }
public string Note { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/CustomerDTO.cs | C# | asf20 | 860 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DTO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DTO")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0ab44e5e-1633-48b0-a4ad-6dbf748662a0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/Properties/AssemblyInfo.cs | C# | asf20 | 1,418 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class PayMoneyDTO
{
public int PayMoneyID { get; set; }
public string PayMoneyCode { get; set; }
public int PayMoneyUserID { get; set; }
public int PayMoneyCustomerID { get; set; }
public DateTime PayMoneyCreateDate { get; set; }
public int Money { get; set; }
public bool Status { get; set; }
public string PayMoneyNote { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/PayMoneyDTO.cs | C# | asf20 | 561 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class InvoiceDetailDTO
{
public int InvoiceDetailID { get; set; }
public int BookID { get; set; }
public int InvoiceID { get; set; }
public int Quantity { get; set; }
public float UnitPrice { get; set; }
public bool Status { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/InvoiceDetailDTO.cs | C# | asf20 | 441 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class ParameterDTO
{
public int ParameterID { get; set; }
public string ParameterCode { get; set; }
public string ParameterName { get; set; }
public int Value { get; set; }
public bool Status { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/ParameterDTO.cs | C# | asf20 | 399 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class BookReportDTO
{
public int BookID { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
public string CategoryName { get; set; }
public int StockQuantity { get; set; }
public int ReceiveQuantity { get; set; }
public int SellQuantity { get; set; }
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/DTO/BookReportDTO.cs | C# | asf20 | 504 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Book
{
public partial class FrmCategoryList : DevComponents.DotNetBar.Office2007Form
{
#region Private Variable
BindingList<CategoryDTO> listCateBinding;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hơặc vừa thêm mới
CategoryBUS categoryBUS;
RuleObjectBUS RuleBUS;
#endregion Private Variable
#region Constructor
public FrmCategoryList()
{
InitializeComponent();
dtgCategoryList.AutoGenerateColumns = false;
categoryBUS = new CategoryBUS();
listCateBinding = new BindingList<CategoryDTO>();
RuleBUS = new RuleObjectBUS();
rowIndex = 0;
}
#endregion Constructor
#region Private Methods
private void CategoryList_Load(object sender, EventArgs e)
{
listCateBinding = categoryBUS.GetNewBindingListCategory();
dtgCategoryList.DataSource = listCateBinding;
this.VisibleChanged += new EventHandler(CategoryList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
void CategoryList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgCategoryList, colNumber.Index);
Global.GenerateEditColumn(dtgCategoryList, colEdit.Index);
Global.GenerateDeleteColumn(dtgCategoryList, colDel.Index);
}
}
private void dtgCategoryList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//if (e.ColumnIndex == colEdit.Index)
//{
// UpdateCategory(e.RowIndex);
//}
//else if (e.ColumnIndex == colDel.Index)
//{
// DeleteCategory();
//}
}
#endregion Private Methods
#region Public Methods
public void CategoryChanged(CategoryDTO cateDTO)
{
CategoryDTO categoryDTO = categoryBUS.GetCategoryByID(cateDTO.CategoryID);
dtgCategoryList[colCategoryName.Index, rowIndex].Value = categoryDTO.CategoryName;
}
public void CategoryChangeAfterInsert(CategoryDTO cateDTO)
{
CategoryDTO categoryDTO = categoryBUS.GetCategoryByID(cateDTO.CategoryID);
listCateBinding.Add(categoryDTO);
rowIndex = dtgCategoryList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgCategoryList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgCategoryList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
//Global.GenerateNumber(dtgCategoryList, colNumber.Index);
if (rowIndex == 0)
{
dtgCategoryList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgCategoryList[colNumber.Index, rowIndex].Value = dtgCategoryList[colNumber.Index, rowIndex - 1].Value.ToString();
}
}
#endregion Public Methods
#region Button,Delete, Update
private void btnDel_Click(object sender, EventArgs e)
{
DeleteCategory();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateCategory(dtgCategoryList.CurrentRow.Index);
}
private void dtgCategoryList_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
UpdateCategory(e.RowIndex);
}
else if (e.ColumnIndex == colDel.Index)
{
DeleteCategory();
}
}
}
private void DeleteCategory()
{
if (dtgCategoryList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionCategory))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa thể loại này ?") == DialogResult.Yes)
{
int success = 0, faile = 0;
foreach (DataGridViewRow row in dtgCategoryList.SelectedRows)
{
int cateID = int.Parse(row.Cells[colCategoryID.Index].Value.ToString());
if (categoryBUS.DeleteCategory(cateID))
{
listCateBinding.Remove(listCateBinding.First(c => c.CategoryID == cateID));
success++;
}
else
{
faile++;
}
}
Global.SetMessage(lblMessage, string.Format("Xóa thành công : {0} dòng, thất bại : {1} dòng.", success, faile), true);
}
}
}
private void UpdateCategory(int index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionCategory))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
rowIndex = index;
CategoryDTO categoryDTO = new CategoryDTO
{
CategoryID = int.Parse(dtgCategoryList[colCategoryID.Index, rowIndex].Value.ToString()),
CategoryCode = dtgCategoryList[colCategoryCode.Index, rowIndex].Value.ToString(),
CategoryName = dtgCategoryList[colCategoryName.Index, rowIndex].Value.ToString()
};
Book.FrmCategoryDetail frm = new FrmCategoryDetail { Category = categoryDTO, Action = ActionName.Update };
//frm.OnCategoryChanged += new Book.FrmCategoryDetail.CategoryHasChanged(CategoryChanged);
frm.ShowDialog();
}
#endregion Button, Delete, Update
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmCategoryList.cs | C# | asf20 | 6,905 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Book
{
public partial class FrmCategoryDetail : DevComponents.DotNetBar.Office2007Form
{
CategoryBUS categoryBus;
public ActionName Action { get; set; }
public CategoryDTO Category { get; set; }
#region Constructor
public FrmCategoryDetail()
{
InitializeComponent();
categoryBus = new CategoryBUS();
btnUpdate.Location = btnAdd.Location;
}
#endregion Constructor
#region Private Methods
private void CategoryDetail_Load(object sender, EventArgs e)
{
if (Action == ActionName.Insert)
{
DocSequenceBUS docsequenceBus = new DocSequenceBUS();
txtCategoryCode.Text = docsequenceBus.GetNextDocSequenceNumber(DocSequence.Category.ToString());
txtCategoryName.Focus();
Category = new CategoryDTO();
}
else
{
txtCategoryCode.Text = Category.CategoryCode;
txtCategoryName.Text = Category.CategoryName;
}
ProcessButton();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Category.CategoryCode = txtCategoryCode.Text;
Category.CategoryName = txtCategoryName.Text;
if (!CheckDataInput())
{
return;
}
Category.CategoryID = categoryBus.InsertCategory(Category);
if (Category.CategoryID > 0)
{
Global.SetMessage(lblMessage, "Thêm thành công!", true);
Action = ActionName.Update;
ProcessButton();
Book.FrmCategoryList frmList = (Book.FrmCategoryList)Application.OpenForms["FrmCategoryList"];
if (frmList != null)
{
frmList.CategoryChangeAfterInsert(Category);
}
//OnCategoryChanged(Category);
}
else
{
Global.SetMessage(lblMessage, "Thêm không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtCategoryCode.Text) || string.IsNullOrEmpty(txtCategoryName.Text))
{
Global.SetMessage(lblMessage, "Tên thể loại không được trống!", false);
txtCategoryName.Focus();
return false;
}
return true;
}
public void ResetForm()
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtCategoryName.Text = string.Empty;
txtCategoryCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Category.ToString());
txtCategoryName.Focus();
}
#region Button
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
Action = ActionName.Insert;
ProcessButton();
Category = new CategoryDTO();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if(!CheckDataInput())
{
return;
}
Category.CategoryName = txtCategoryName.Text;
if (categoryBus.UpdateCategory(Category))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
//OnCategoryChanged(Category);
Book.FrmCategoryList frmList = (Book.FrmCategoryList)Application.OpenForms["FrmCategoryList"];
if (frmList != null)
{
frmList.CategoryChanged(Category);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
#endregion Button
private void CategoryDetail_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
switch (Action)
{
case ActionName.Insert:
btnAdd_Click(sender, e);
break;
case ActionName.Update:
btnUpdate_Click(sender, e);
break;
}
}
}
#endregion Private Methods
//public delegate void CategoryHasChanged(CategoryDTO cateDTO);
//public event CategoryHasChanged OnCategoryChanged;
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmCategoryDetail.cs | C# | asf20 | 5,375 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Book
{
public partial class FrmBookDetail : DevComponents.DotNetBar.Office2007Form
{
public ActionName Action { get; set; }
public int _bookID { get; set; }
BookBUS bookBUS;
public FrmBookDetail()
{
InitializeComponent();
btnUpdate.Location = btnAdd.Location;
dbiBookCost.DisplayFormat = Global.NumberFormat;
dbiBookCost.Value = 0;
dbiReceivePrice.DisplayFormat = Global.NumberFormat;
dbiReceivePrice.Value = 0;
cmbAuthor.DisplayMember = Author.AuthorName.ToString();
cmbAuthor.ValueMember = Author.AuthorID.ToString();
cmbCategory.DisplayMember = Category.CategoryName.ToString();
cmbCategory.ValueMember = Category.CategoryID.ToString();
bookBUS = new BookBUS();
}
private void FrmBookDetail_Load(object sender, EventArgs e)
{
LoadCategoryList();
LoadAuthorList();
if (Action == ActionName.Insert)
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtBookCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Book.ToString());
}
else
{
BookDTO bookDto = bookBUS.GetBookByID(_bookID);
txtBookCode.Text = bookDto.BookCode;
txtBookName.Text = bookDto.BookName;
cmbAuthor.SelectedValue = bookDto.AuthorID;
cmbCategory.SelectedValue = bookDto.CategoryID;
dbiBookCost.Value = bookDto.BookCost;
dbiReceivePrice.Value = bookDto.ReceivePrice;
}
ProcessButton();
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtBookName.Text))
{
Global.SetMessage(lblMessage, "Tên sách không được trống!", false);
txtBookName.Focus();
return false;
}
else if (dbiBookCost.Value <= 0)
{
Global.SetMessage(lblMessage, "Giá bán phải lớn hơn 0.", false);
dbiBookCost.Focus();
return false;
}
else if (dbiReceivePrice.Value <= 0)
{
Global.SetMessage(lblMessage, "Giá nhập phải lớn hơn 0.", false);
dbiReceivePrice.Focus();
return false;
}
return true;
}
private void LoadCategoryList()
{
CategoryBUS cateBUS = new CategoryBUS();
cmbCategory.DataSource = cateBUS.GetCategoryList();
}
private void LoadAuthorList()
{
AuthorBUS authorBUS = new AuthorBUS();
cmbAuthor.DataSource = authorBUS.GetNewBindingListAuthor();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
}
}
private void btnAddCategory_Click(object sender, EventArgs e)
{
Book.FrmCategoryDetail frm = new FrmCategoryDetail { Action = ActionName.Insert };
frm.ShowDialog();
LoadCategoryList();
}
private void btnAddAuthor_Click(object sender, EventArgs e)
{
Book.FrmAuthorDetail frm = new FrmAuthorDetail { Action = ActionName.Insert };
frm.ShowDialog();
LoadAuthorList();
}
private BookDTO MapBookDTOFromUI()
{
BookDTO bookDto = new BookDTO
{
BookCode = txtBookCode.Text,
BookName = txtBookName.Text,
BookCost = float.Parse(dbiBookCost.Value.ToString()),
ReceivePrice = float.Parse(dbiReceivePrice.Value.ToString()),
AuthorID = int.Parse(cmbAuthor.SelectedValue.ToString()),
CategoryID = int.Parse(cmbCategory.SelectedValue.ToString())
};
return bookDto;
}
private void btnAdd_Click(object sender, EventArgs e)
{
if(!CheckDataInput())
{
return;
}
BookDTO bookDto = MapBookDTOFromUI();
_bookID = bookBUS.InsertBook(bookDto);
if (_bookID > 0)
{
Global.SetMessage(lblMessage, "Thêm sách mới thành công!", true);
Action = ActionName.Update;
ProcessButton();
Book.FrmBookList frm = (Book.FrmBookList)Application.OpenForms["FrmBookList"];
if (frm != null)
{
frm.BookListChangeAfterInsert(_bookID);
}
}
else
{
Global.SetMessage(lblMessage, "Thêm sách thất bại!", false);
}
}
private void ResetForm()
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtBookCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Book.ToString());
Action = ActionName.Insert;
ProcessButton();
txtBookName.Clear();
LoadAuthorList();
LoadCategoryList();
txtBookName.Focus();
}
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
BookDTO bookDto = MapBookDTOFromUI();
bookDto.BookID = _bookID;
if (bookBUS.UpdateBook(bookDto))
{
Global.SetMessage(lblMessage, "Sửa thông tin sách thành công!", true);
Book.FrmBookList frm = (Book.FrmBookList)Application.OpenForms["FrmBookList"];
if (frm != null)
{
frm.BookChangeAfterUpdate(_bookID);
}
}
else
{
Global.SetMessage(lblMessage, "Sửa thông tin sách không thành công!", false);
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmBookDetail.cs | C# | asf20 | 6,918 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Book
{
public partial class FrmBookList : DevComponents.DotNetBar.Office2007Form
{
BindingList<BookDTO> _listBook;
BindingList<BookDTO> _listBookSearch;
bool _isSearching;
BookBUS _bookBUS;
RuleObjectBUS RuleBUS;
int rowIndex = -1;
public FrmBookList()
{
InitializeComponent();
_listBook = new BindingList<BookDTO>();
_listBookSearch = new BindingList<BookDTO>();
_bookBUS = new BookBUS();
RuleBUS = new RuleObjectBUS();
dtgBookList.AutoGenerateColumns = false;
_isSearching = false;
dbiTo.DisplayFormat = "N0";
dbiFrom.DisplayFormat = "N0";
dbiFrom.Value = 0;
dbiTo.Value = 20000;
}
private void FrmBookList_Load(object sender, EventArgs e)
{
this.VisibleChanged += new EventHandler(FrmBookList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDelete.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDelete.Enabled;
}
void FrmBookList_VisibleChanged(object sender, EventArgs e)
{
LoadListBook();
}
private void LoadListBook()
{
_listBook = _bookBUS.GetNewBindingList();
dtgBookList.DataSource = _listBook;
GenerateGridColumn();
}
private void GenerateGridColumn()
{
Global.GenerateDeleteColumn(dtgBookList, colDel.Index);
Global.GenerateEditColumn(dtgBookList, colEdit.Index);
Global.GenerateNumber(dtgBookList, colNumber.Index);
}
private BindingList<BookDTO> GetBindingList(List<BookDTO> list)
{
BindingList<BookDTO> bingdingList = new BindingList<BookDTO>();
foreach (BookDTO book in list)
{
bingdingList.Add(book);
}
return bingdingList;
}
private void btnSearch_Click(object sender, EventArgs e)
{
_listBookSearch = GetBindingList( _listBook.Where(b => b.BookCode.Contains(txtBookCode.Text) &&
b.BookName.ToUpper().Contains(txtBookName.Text.ToUpper()) &&
b.BookCost > dbiFrom.Value && b.BookCost < dbiTo.Value).ToList<BookDTO>());
dtgBookList.DataSource = _listBookSearch;
GenerateGridColumn();
_isSearching = true;
}
private void btnViewAll_Click(object sender, EventArgs e)
{
ClearForm();
LoadListBook();
}
public void BookListChangeAfterInsert(int id)
{
BookDTO bookDto = _bookBUS.GetBookByID(id);
if (_isSearching)
{
_listBookSearch.Add(bookDto);
}
else
{
_listBook.Add(bookDto);
}
rowIndex = dtgBookList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgBookList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgBookList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
if (rowIndex == 0)
{
dtgBookList[colNumber.Index, rowIndex].Value = 1;
}
else
{
dtgBookList[colNumber.Index, rowIndex].Value = int.Parse(dtgBookList[colNumber.Index, rowIndex - 1].Value.ToString()) + 1;
}
}
public void BookChangeAfterUpdate(int id)
{
BookDTO bookDto = _bookBUS.GetBookByID(id);
dtgBookList[colBookName.Index, rowIndex].Value = bookDto.BookName;
dtgBookList[colAuthor.Index, rowIndex].Value = bookDto.AuthorName;
dtgBookList[colCategory.Index, rowIndex].Value = bookDto.CategoryName;
dtgBookList[colCost.Index, rowIndex].Value = bookDto.BookCost;
}
private void dtgBookList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
rowIndex = e.RowIndex;
UpdateBook();
}
else if (e.ColumnIndex == colDel.Index)
{
DeleteBook();
}
}
}
private void DeleteBook()
{
if (dtgBookList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa sách này ?") == DialogResult.Yes)
{
int success = 0, faile = 0;
foreach (DataGridViewRow row in dtgBookList.SelectedRows)
{
int bookID = int.Parse(row.Cells[colBookID.Index].Value.ToString());
if (_bookBUS.DeleteBook(bookID))
{
//dtgBookList.Rows.Remove(row);
if (_isSearching)
{
_listBookSearch.Remove(_listBookSearch.First(c => c.BookID == bookID));
}
else
{
_listBook.Remove(_listBook.First(c => c.BookID == bookID));
}
success++;
}
else
{
faile++;
}
}
Global.SetMessage(lblMessage, string.Format("Xóa thành công : {0} dòng, thất bại : {1} dòng.", success, faile), true);
Global.GenerateNumber(dtgBookList, colNumber.Index);
}
}
}
private void UpdateBook()
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
int id = int.Parse(dtgBookList[colBookID.Index,rowIndex].Value.ToString());
Book.FrmBookDetail frm = new FrmBookDetail { Action = ActionName.Update, _bookID = id };
frm.ShowDialog();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dtgBookList.Rows.Count > 0)
{
rowIndex = dtgBookList.CurrentRow.Index;
UpdateBook();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
DeleteBook();
}
private void ClearForm()
{
txtBookCode.Clear();
txtBookName.Clear();
txtBookCode.Focus();
_isSearching = false;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmBookList.cs | C# | asf20 | 7,850 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Book
{
public partial class FrmBookListSearch : DevComponents.DotNetBar.Office2007Form
{
BindingList<BookDTO> _listBook;
BindingList<BookDTO> _listBookSearch;
bool _isSearching;
BookBUS _bookBUS;
RuleObjectBUS RuleBUS;
int rowIndex = -1;
public FrmBookListSearch()
{
InitializeComponent();
_listBook = new BindingList<BookDTO>();
_listBookSearch = new BindingList<BookDTO>();
_bookBUS = new BookBUS();
RuleBUS = new RuleObjectBUS();
dtgBookList.AutoGenerateColumns = false;
_isSearching = false;
dbiTo.DisplayFormat = "N0";
dbiFrom.DisplayFormat = "N0";
dbiFrom.Value = 0;
dbiTo.Value = 20000;
}
private void FrmBookList_Load(object sender, EventArgs e)
{
this.VisibleChanged += new EventHandler(FrmBookList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDelete.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDelete.Enabled;
}
void FrmBookList_VisibleChanged(object sender, EventArgs e)
{
LoadListBook();
}
private void LoadListBook()
{
_listBook = _bookBUS.GetNewBindingList();
dtgBookList.DataSource = _listBook;
GenerateGridColumn();
}
private void ClearForm()
{
txtAuthor.Clear();
txtBookCode.Clear();
txtBookName.Clear();
txtCategory.Clear();
txtBookCode.Focus();
_isSearching = false;
}
private void GenerateGridColumn()
{
Global.GenerateDeleteColumn(dtgBookList, colDel.Index);
Global.GenerateEditColumn(dtgBookList, colEdit.Index);
Global.GenerateNumber(dtgBookList, colNumber.Index);
}
private BindingList<BookDTO> GetBindingList(List<BookDTO> list)
{
BindingList<BookDTO> bingdingList = new BindingList<BookDTO>();
foreach (BookDTO book in list)
{
bingdingList.Add(book);
}
return bingdingList;
}
private void btnSearch_Click(object sender, EventArgs e)
{
_listBookSearch = GetBindingList( _listBook.Where(b => b.BookCode.Contains(txtBookCode.Text) &&
b.BookName.ToUpper().Contains(txtBookName.Text.ToUpper()) &&
b.BookCost > dbiFrom.Value && b.BookCost < dbiTo.Value &&
b.CategoryName.ToUpper().Contains(txtCategory.Text.ToUpper()) &&
b.AuthorName.ToUpper().Contains(txtAuthor.Text.ToUpper())).ToList());
dtgBookList.DataSource = _listBookSearch;
GenerateGridColumn();
_isSearching = true;
}
private void btnViewAll_Click(object sender, EventArgs e)
{
LoadListBook();
ClearForm();
}
public void BookListChangeAfterInsert(int id)
{
BookDTO bookDto = _bookBUS.GetBookByID(id);
_listBook.Add(bookDto);
rowIndex = dtgBookList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgBookList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgBookList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
if (rowIndex == 0)
{
dtgBookList[colNumber.Index, rowIndex].Value = 1;
}
else
{
dtgBookList[colNumber.Index, rowIndex].Value = int.Parse(dtgBookList[colNumber.Index, rowIndex - 1].Value.ToString()) + 1;
}
}
public void BookChangeAfterUpdate(int id)
{
BookDTO bookDto = _bookBUS.GetBookByID(id);
dtgBookList[colBookName.Index, rowIndex].Value = bookDto.BookName;
dtgBookList[colAuthor.Index, rowIndex].Value = bookDto.AuthorName;
dtgBookList[colCategory.Index, rowIndex].Value = bookDto.CategoryName;
dtgBookList[colCost.Index, rowIndex].Value = bookDto.BookCost;
}
private void dtgBookList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
rowIndex = e.RowIndex;
UpdateBook();
}
else if (e.ColumnIndex == colDel.Index)
{
DeleteBook();
}
}
}
private void DeleteBook()
{
if (dtgBookList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa sách này ?") == DialogResult.Yes)
{
int success = 0, faile = 0;
foreach (DataGridViewRow row in dtgBookList.SelectedRows)
{
int bookID = int.Parse(row.Cells[colBookID.Index].Value.ToString());
if (_bookBUS.DeleteBook(bookID))
{
if (_isSearching)
{
_listBookSearch.Remove(_listBookSearch.First(c => c.BookID == bookID));
}
else
{
_listBook.Remove(_listBook.First(c => c.BookID == bookID));
}
success++;
}
else
{
faile++;
}
}
Global.SetMessage(lblMessage, string.Format("Xóa thành công : {0} dòng, thất bại : {1} dòng.", success, faile), true);
Global.GenerateNumber(dtgBookList, colNumber.Index);
}
}
}
private void UpdateBook()
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
int id = int.Parse(dtgBookList[colBookID.Index,rowIndex].Value.ToString());
Book.FrmBookDetail frm = new FrmBookDetail { Action = ActionName.Update, _bookID = id };
frm.ShowDialog();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dtgBookList.Rows.Count > 0)
{
rowIndex = dtgBookList.CurrentRow.Index;
UpdateBook();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
DeleteBook();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmBookListSearch.cs | C# | asf20 | 7,822 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Book
{
public partial class FrmAuthorList : DevComponents.DotNetBar.Office2007Form
{
BindingList<AuthorDTO> listAuthorBinding;
AuthorBUS authorBUS;
RuleObjectBUS RuleBUS;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hoặc vừa thêm mới
public FrmAuthorList()
{
InitializeComponent();
dtgAuthorList.AutoGenerateColumns = false;
authorBUS = new AuthorBUS();
listAuthorBinding = new BindingList<AuthorDTO>();
RuleBUS = new RuleObjectBUS();
rowIndex = 0;
}
private void FrmAuthorList_Load(object sender, EventArgs e)
{
listAuthorBinding = authorBUS.GetNewBindingListAuthor();
dtgAuthorList.DataSource = listAuthorBinding;
this.VisibleChanged += new EventHandler(FrmAuthorList_VisibleChanged);
CheckPermission();
}
void FrmAuthorList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgAuthorList, colNumber.Index);
Global.GenerateEditColumn(dtgAuthorList, colEdit.Index);
Global.GenerateDeleteColumn(dtgAuthorList, colDel.Index);
}
}
private void dtgAuthorList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
UpdateAuthor(e.RowIndex);
}
else if (e.ColumnIndex == colDel.Index)
{
DeleteAuthor();
}
}
}
public void AuthorChanged(AuthorDTO authorDto)
{
dtgAuthorList[colAuthorName.Index, rowIndex].Value = authorDto.AuthorName;
}
public void AuthorChangeAfterInsert(AuthorDTO authorDTO)
{
AuthorDTO authDTO = authorBUS.GetAuthorByID(authorDTO.AuthorID);
listAuthorBinding.Add(authDTO);
rowIndex = dtgAuthorList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgAuthorList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgAuthorList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
if (rowIndex == 0)
{
dtgAuthorList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgAuthorList[colNumber.Index, rowIndex].Value = dtgAuthorList[colNumber.Index, rowIndex - 1].Value.ToString();
}
}
private void btnDel_Click(object sender, EventArgs e)
{
DeleteAuthor();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dtgAuthorList.Rows.Count > 0)
{
UpdateAuthor(dtgAuthorList.CurrentRow.Index);
}
}
private void UpdateAuthor(int index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
AuthorDTO authorDTO = new AuthorDTO
{
AuthorID = int.Parse(dtgAuthorList[colAuthorID.Index, index].Value.ToString()),
AuthorCode = dtgAuthorList[colAuthorCode.Index, index].Value.ToString(),
AuthorName = dtgAuthorList[colAuthorName.Index, index].Value.ToString()
};
rowIndex = index;
Book.FrmAuthorDetail frm = new FrmAuthorDetail { AuthorDto = authorDTO, Action = ActionName.Update };
frm.ShowDialog();
}
private void DeleteAuthor()
{
if (dtgAuthorList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa tác giả này ?") == DialogResult.Yes)
{
int success = 0, faile = 0;
foreach (DataGridViewRow row in dtgAuthorList.SelectedRows)
{
int authorID = int.Parse(row.Cells[colAuthorID.Index].Value.ToString());
if (authorBUS.DeleteAuthor(authorID))
{
listAuthorBinding.Remove(listAuthorBinding.First(c => c.AuthorID == authorID));
success++;
}
else
{
faile++;
}
}
Global.SetMessage(lblMessage,string.Format("Xóa thành công : {0} dòng, thất bại : {1} dòng.",success,faile),true);
}
}
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmAuthorList.cs | C# | asf20 | 5,865 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Book
{
public partial class FrmAuthorDetail : DevComponents.DotNetBar.Office2007Form
{
AuthorBUS authorBUS;
public ActionName Action { get; set; }
public AuthorDTO AuthorDto { get; set; }
public FrmAuthorDetail()
{
InitializeComponent();
authorBUS = new AuthorBUS();
btnUpdate.Location = btnAdd.Location;
}
private void AuthorDetail_Load(object sender, EventArgs e)
{
if (Action == ActionName.Insert)
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtAuthorCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Author.ToString());
txtAuthorName.Focus();
AuthorDto = new AuthorDTO();
}
else
{
txtAuthorCode.Text = AuthorDto.AuthorCode;
txtAuthorName.Text = AuthorDto.AuthorName;
}
ProcessButton();
}
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorDto.AuthorCode = txtAuthorCode.Text;
AuthorDto.AuthorName = txtAuthorName.Text;
if (!CheckDataInput())
{
return;
}
AuthorDto.AuthorID = authorBUS.InsertAuthor(AuthorDto);
if (AuthorDto.AuthorID > 0)
{
Global.SetMessage(lblMessage, "Thêm thành công!", true);
Action = ActionName.Update;
ProcessButton();
Book.FrmAuthorList frmList = (Book.FrmAuthorList)Application.OpenForms["FrmAuthorList"];
if (frmList != null)
{
frmList.AuthorChangeAfterInsert(AuthorDto);
}
//OnCategoryChanged(Category);
}
else
{
Global.SetMessage(lblMessage, "Thêm không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtAuthorCode.Text) || string.IsNullOrEmpty(txtAuthorName.Text))
{
Global.SetMessage(lblMessage, "Tên tác giả không được trống!", false);
return false;
}
return true;
}
public void ResetForm()
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtAuthorName.Text = string.Empty;
txtAuthorCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Author.ToString());
txtAuthorName.Focus();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
AuthorDto.AuthorName = txtAuthorName.Text;
if (authorBUS.UpdateAuthor(AuthorDto))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
//OnCategoryChanged(Category);
Book.FrmAuthorList frmList = (Book.FrmAuthorList)Application.OpenForms["FrmAuthorList"];
if (frmList != null)
{
frmList.AuthorChanged(AuthorDto);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
Action = ActionName.Insert;
ProcessButton();
AuthorDto = new AuthorDTO();
}
private void FrmAuthorDetail_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
switch (Action)
{
case ActionName.Insert:
btnAdd_Click(sender, e);
break;
case ActionName.Update:
btnUpdate_Click(sender, e);
break;
}
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Book/FrmAuthorDetail.cs | C# | asf20 | 4,920 |