Организация удаленного доступа к распределенным базам данных

Основные понятия теории реляционных баз данных. Технология и модели "клиент-сервер". Применение CASE-средств для информационного моделирования в системах обработки данных. Использование слоя RPC для распределенной обработки данных на платформе Windows NT.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 19.06.2011
Размер файла 462,9 K

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

UPDATE UslProps

SET BegDate = new.EndDate

WHERE ((new.EndDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

UPDATE UslProps

SET EndDate = new.BegDate

WHERE ((new.BegDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

END ^

CREATE TRIGGER UslProps_BDH FOR UslProps

BEFORE DELETE POSITION 0

AS

BEGIN

UPDATE UslProps

SET EndDate = old.EndDate

WHERE ((EndDate = old.BegDate) AND (PKey = old.PKey));

END ^

CREATE TABLE UslPropsKeys (

Code INTEGER NOT NULL

);

ALTER TABLE UslPropsKeys

ADD CONSTRAINT XPKUslPropsKeys PRIMARY KEY (Code);

CREATE TABLE Usls (

Code INTEGER NOT NULL,

PKey INTEGER NOT NULL,

Division INTEGER NOT NULL,

UslType INTEGER NOT NULL,

Name CHAR(64) NOT NULL,

BegDate DATE_TYPE,

EndDate DATE_TYPE

);

CREATE INDEX XIEUslsName ON Usls

(

Name

);

ALTER TABLE Usls

ADD CONSTRAINT XPKUsls PRIMARY KEY (Code);

CREATE TRIGGER Usls_BUH FOR Usls

BEFORE UPDATE POSITION 0

AS

BEGIN

/* Изменение BegDate */

IF (new.BegDate <> old.BegDate) THEN

BEGIN

IF (new.BegDate < old.BegDate) THEN

BEGIN

/* Расширение BegDate */

UPDATE Usls

SET EndDate = new.BegDate

WHERE ((new.BegDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

END

ELSE

BEGIN

/* Сужение BegDate */

UPDATE Usls

SET EndDate = new.BegDate

WHERE ((EndDate = old.BegDate) AND (PKey = new.PKey));

END

END

/* Изменение EndDate */

IF (new.EndDate <> old.EndDate) THEN

BEGIN

IF (new.EndDate > old.EndDate) THEN

BEGIN

/* Расширение EndDate */

UPDATE Usls

SET BegDate = new.EndDate

WHERE ((new.EndDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

END

ELSE

BEGIN

/* Сужение EndDate */

UPDATE Usls

SET BegDate = new.EndDate

WHERE ((BegDate = old.EndDate) AND (PKey = new.PKey));

END

END

/* Сборка мусора */

DELETE FROM Usls

WHERE ((BegDate >= new.BegDate) AND (EndDate <= new.EndDate) AND (PKey = new.PKey) AND (Code <> new.Code));

END ^

CREATE TRIGGER Usls_BIH FOR Usls

BEFORE INSERT POSITION 0

AS

BEGIN

DELETE FROM Usls

WHERE ((BegDate >= new.BegDate) AND (EndDate <= new.EndDate) AND (PKey = new.PKey));

UPDATE Usls

SET BegDate = new.EndDate

WHERE ((new.EndDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

UPDATE Usls

SET EndDate = new.BegDate

WHERE ((new.BegDate BETWEEN BegDate AND EndDate) AND (PKey = new.PKey));

END ^

CREATE TRIGGER Usls_BDH FOR Usls

BEFORE DELETE POSITION 0

AS

BEGIN

UPDATE Usls

SET EndDate = old.EndDate

WHERE ((EndDate = old.BegDate) AND (PKey = old.PKey));

END ^

CREATE TABLE UslsKeys (

Code INTEGER NOT NULL

);

ALTER TABLE UslsKeys

ADD CONSTRAINT XPKUslsKeys PRIMARY KEY (Code);

CREATE TABLE UslTypes (

Code INTEGER NOT NULL,

Name DESCR_TYPE

);

ALTER TABLE UslTypes

ADD CONSTRAINT XPKUslTypes PRIMARY KEY (Code);

ALTER TABLE Nach

ADD CONSTRAINT R_59

FOREIGN KEY (Usl)

REFERENCES UslsKeys;

ALTER TABLE Nach

ADD CONSTRAINT R_57

FOREIGN KEY (Phone)

REFERENCES PhonesKeys;

ALTER TABLE Nach

ADD FOREIGN KEY (Owner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE NachBillings

ADD CONSTRAINT R_65

FOREIGN KEY (Division)

REFERENCES UslDivisionsKeys;

ALTER TABLE NachBillings

ADD FOREIGN KEY (BillDateCode)

REFERENCES NachBillDates;

ALTER TABLE NachBillings

ADD FOREIGN KEY (Owner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE NachConstUsl

ADD CONSTRAINT R_60

FOREIGN KEY (Usl)

REFERENCES UslsKeys;

ALTER TABLE NachConstUsl

ADD CONSTRAINT R_58

FOREIGN KEY (Phone)

REFERENCES PhonesKeys;

ALTER TABLE NachConstUsl

ADD FOREIGN KEY (Owner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE Phones

ADD FOREIGN KEY (Owner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE Phones

ADD FOREIGN KEY (PKey)

REFERENCES PhonesKeys;

ALTER TABLE Phones

ADD FOREIGN KEY (Street)

REFERENCES PhonesStreets;

ALTER TABLE PhonesOwners

ADD FOREIGN KEY (PostStation)

REFERENCES PhonesPostStations;

ALTER TABLE PhonesOwners

ADD FOREIGN KEY (Street)

REFERENCES PhonesStreets;

ALTER TABLE PhonesOwners

ADD FOREIGN KEY (Bank)

REFERENCES PhonesBanks;

ALTER TABLE PhonesOwners

ADD FOREIGN KEY (Category)

REFERENCES UslCatKeys;

ALTER TABLE PhonesOwners

ADD FOREIGN KEY (PKey)

REFERENCES PhonesOwnersKeys;

ALTER TABLE PhonesPostStations

ADD CONSTRAINT R_62

FOREIGN KEY (Region)

REFERENCES PhonesRegions;

ALTER TABLE PhonesStations

ADD FOREIGN KEY (Region)

REFERENCES PhonesRegions;

ALTER TABLE PhonesStreets

ADD FOREIGN KEY (Region)

REFERENCES PhonesRegions;

ALTER TABLE PhonesStreets

ADD FOREIGN KEY (Station)

REFERENCES PhonesStations;

ALTER TABLE Plat

ADD CONSTRAINT R_61

FOREIGN KEY (ToUsl)

REFERENCES UslsKeys;

ALTER TABLE Plat

ADD FOREIGN KEY (Owner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE SysSettings

ADD FOREIGN KEY (NullOwner)

REFERENCES PhonesOwnersKeys;

ALTER TABLE SysSettings

ADD FOREIGN KEY (TimeTalksUsl)

REFERENCES UslsKeys;

ALTER TABLE Talks

ADD FOREIGN KEY (ToPhone)

REFERENCES PhonesKeys;

ALTER TABLE Talks

ADD FOREIGN KEY (Phone)

REFERENCES PhonesKeys;

ALTER TABLE Talks

ADD FOREIGN KEY (DayCode)

REFERENCES TalksPay;

ALTER TABLE TalksPay

ADD FOREIGN KEY (Phone)

REFERENCES PhonesKeys;

ALTER TABLE UslCat

ADD FOREIGN KEY (PKey)

REFERENCES UslCatKeys;

ALTER TABLE UslDivisions

ADD CONSTRAINT R_63

FOREIGN KEY (PKey)

REFERENCES UslDivisionsKeys;

ALTER TABLE UslLgots

ADD CONSTRAINT R_50

FOREIGN KEY (Property)

REFERENCES UslPropsKeys;

ALTER TABLE UslLgots

ADD FOREIGN KEY (Usl)

REFERENCES UslsKeys;

ALTER TABLE UslLgots

ADD FOREIGN KEY (Category)

REFERENCES UslCatKeys;

ALTER TABLE UslProps

ADD CONSTRAINT R_51

FOREIGN KEY (PKey)

REFERENCES UslPropsKeys;

ALTER TABLE Usls

ADD CONSTRAINT R_64

FOREIGN KEY (Division)

REFERENCES UslDivisionsKeys;

ALTER TABLE Usls

ADD FOREIGN KEY (UslType)

REFERENCES UslTypes;

ALTER TABLE Usls

ADD FOREIGN KEY (PKey)

REFERENCES UslsKeys;

CREATE PROCEDURE PrGenUslPropsKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslPropsKeys, 1);

END ^

CREATE PROCEDURE PrGenUslProps

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslProps, 1);

END ^

CREATE PROCEDURE PrGenPhonesRegions

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesRegions, 1);

END ^

CREATE PROCEDURE PrGenPhonesStations

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesStations, 1);

END ^

CREATE PROCEDURE PrGenPhonesStreets

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesStreets, 1);

END ^

CREATE PROCEDURE PrGenPhonesBanks

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesBanks, 1);

END ^

CREATE PROCEDURE PrGenTalksPay

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genTalksPay, 1);

END ^

CREATE PROCEDURE PrGenTalks

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genTalks, 1);

END ^

CREATE PROCEDURE PrGenNach

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genNach, 1);

END ^

CREATE PROCEDURE PrGenNachBillings

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genNachBillings, 1);

END ^

CREATE PROCEDURE PrGenNachBillDates

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genNachBillDates, 1);

END ^

CREATE PROCEDURE PrGenNachConstUsl

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genNachConstUsl, 1);

END ^

CREATE PROCEDURE PrGenUslDivisions

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslDivisions, 1);

END ^

CREATE PROCEDURE PrGenUslLgots

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslLgots, 1);

END ^

CREATE PROCEDURE PrGenUslsKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslsKeys, 1);

END ^

CREATE PROCEDURE PrGenUsls

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUsls, 1);

END ^

CREATE PROCEDURE PrGenUslCatKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslCatKeys, 1);

END ^

CREATE PROCEDURE PrGenUslCat

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslCat, 1);

END ^

CREATE PROCEDURE PrGenPhones

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhones, 1);

END ^

CREATE PROCEDURE PrGenPhonesOwnersKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesOwnersKeys, 1);

END ^

CREATE PROCEDURE PrGenPhonesOwners

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesOwners, 1);

END ^

CREATE PROCEDURE PrGenSysSettings

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genSysSettings, 1);

END ^

CREATE PROCEDURE PrGenPhonesKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesKeys, 1);

END ^

CREATE PROCEDURE PrGenPlat

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPlat, 1);

END ^

CREATE PROCEDURE PrGenPhonesPostStations

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genPhonesPostStations, 1);

END ^

CREATE PROCEDURE PrGenSysLog

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genSysLog, 1);

END ^

CREATE PROCEDURE PrGenUslTypes

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslTypes, 1);

END ^

CREATE PROCEDURE PrGenUslDivisionsKeys

RETURNS (ACode INTEGER)

AS

BEGIN

ACode = GEN_ID(genUslDivisionsKeys, 1);

END ^

^

CREATE PROCEDURE TalksExamineOwner (APhoneNmb CHAR(7), ADate DATE)

RETURNS (APhone INTEGER)

AS

DECLARE VARIABLE AStreet INTEGER;

DECLARE VARIABLE NOwner INTEGER;

DECLARE VARIABLE APhoneCode INTEGER;

BEGIN

SELECT PKey FROM Phones WHERE (PhoneNmb =:APhoneNmb) AND (:ADate BETWEEN BegDate AND EndDate)

INTO:APhone;

IF (:APhone IS NULL) THEN

BEGIN

SELECT NullOwner FROM SysSettings INTO:NOwner;

SELECT Street FROM PhonesOwners

WHERE (PKey =:NOwner) AND (:ADate BETWEEN PhonesOwners.BegDate AND PhonesOwners.EndDate)

INTO:AStreet;

IF (:AStreet IS NOT NULL) THEN

BEGIN

EXECUTE PROCEDURE PrGenPhonesKeys RETURNING_VALUES:APhone;

INSERT INTO PhonesKeys (Code)

VALUES (:APhone);

INSERT INTO Phones(Owner, PKey, PhoneNmb, Street, InstallDate, RemoveDate, BegDate, EndDate)

VALUES (:NOwner,:APhone,:APhoneNmb,:AStreet,:ADate, "12.12.2222",:ADate, "12.12.2222");

END

END

END ^

CREATE PROCEDURE TalksGetTax

AS

BEGIN

EXIT;

END ^

CREATE PROCEDURE TalksGetPay (APhone INTEGER, ADay DATE, ACallTime INTEGER, AHowLong INTEGER)

RETURNS (APay FLOAT, ACalculated SMALLINT, IsLgot SMALLINT)

AS

DECLARE VARIABLE ATax FLOAT;

DECLARE VARIABLE AProcNach FLOAT;

DECLARE VARIABLE ATalksUsl INTEGER;

DECLARE VARIABLE AOwner INTEGER;

DECLARE VARIABLE ANalog FLOAT;

BEGIN

ACalculated = 0;

SELECT TimeTalksUsl FROM SysSettings INTO:ATalksUsl;

IF (:ATalksUsl IS NULL) THEN EXIT;

SELECT Owner FROM Phones WHERE (PKey =:APhone) AND (:ADay BETWEEN BegDate AND EndDate)

INTO:AOwner;

IF (:AOwner IS NULL) THEN EXIT;

EXECUTE PROCEDURE UslGetOwnerTax(:AOwner,:ATalksUsl,:ADay)

RETURNING_VALUES:ATax,:AProcNach,:ANalog;

IF (:ATax IS NULL) THEN EXIT;

APay = ATax*AHowLong*AProcNach/3000;

ACalculated = 1;

END ^

CREATE PROCEDURE TalksCallBilling (APhone INTEGER, ACallDate DATE, ACallTime INTEGER, AHowLong INTEGER)

RETURNS (ATalksPayCode INTEGER, ACalculated SMALLINT)

AS

DECLARE VARIABLE APay FLOAT;

DECLARE VARIABLE PayCode INTEGER;

DECLARE VARIABLE IsLgot SMALLINT;

DECLARE VARIABLE TTime INTEGER;

DECLARE VARIABLE LTime INTEGER;

BEGIN

EXECUTE PROCEDURE TalksGetPay(APhone, ACallDate, ACallTime, AHowLong)

RETURNING_VALUES:APay,:ACalculated,:IsLgot;

SELECT Code FROM TalksPay WHERE (Phone =:APhone) AND (CallDate =:ACallDate)

INTO PayCode;

IF (:ACalculated = 0) THEN EXIT;

IF (:IsLgot = 0) THEN BEGIN

TTime = AHowLong;

LTime = 0;

END

ELSE BEGIN

LTime = AHowLong;

TTime = 0;

END

IF (:PayCode IS NULL) THEN BEGIN

EXECUTE PROCEDURE PrGenTalksPay RETURNING_VALUES:PayCode;

INSERT INTO TalksPay (Code, Phone, CallDate, TotalSum, TotalFullTime, TotalLgotTime)

VALUES (:PayCode,:APhone,:ACallDate,:APay,:TTime,:LTime);

END

ELSE BEGIN

UPDATE TalksPay

SET TotalSum = TotalSum+:APay,

TotalFullTime = TotalFullTime+:TTime,

TotalLgotTime = TotalLgotTime+:LTime

WHERE Code =:PayCode;

END

END ^

CREATE PROCEDURE UslGetOwnerTax(AOwner INTEGER, AUsl INTEGER, ADate DATE)

RETURNS (ATax FLOAT,

AProcNach FLOAT,

ANalog FLOAT)

AS

DECLARE VARIABLE ACategory INTEGER;

BEGIN

SELECT Category FROM PhonesOwners

WHERE (PKey =:AOwner) AND (:ADate BETWEEN BegDate AND EndDate)

INTO:ACategory;

SELECT Tax, NachCoeff, Nalog FROM UslLgots

WHERE (Usl =:AUsl) AND (:ADate BETWEEN BegDate AND EndDate)

INTO:ATax,:AProcNach,:ANalog;

EXIT;

END

Приложение 2

Приложение 3

Исходные тексты коммуникационного сервиса

ServiceMain.c

Файл ServiceMain.c - Модуль инициализации и управления сервером.

/*************************************************************/

/* Main unit for Communication Service */

/* Copyright (c) 1997 by Malkov O.V. */

/* JSC "Svyazinform" RM */

/*************************************************************/

#include <windows.h>

#include "DoService.h"

#include "CommonConfig.h"

/* Globals */

SERVICE_STATUS ServiceStatus;

SERVICE_STATUS_HANDLE ServiceStatusHandle;

/* Function Prototypes */

void WINAPI ServiceStart (DWORD argc, LPTSTR *argv);

VOID WINAPI ServiceCtrlHandler (IN DWORD opcode);

DWORD ServiceInitialization(DWORD argc, LPTSTR *argv,

DWORD *specificError);

VOID _CRTAPI1 main(int argc, char **argv)

{

int i;

SERVICE_TABLE_ENTRY DispatchTable[] = {

{ TEXT("SiTime"), ServiceStart },

{ NULL, NULL }

};

/* Allow the user to override settings with command line switches */

for ( i = 1; i < argc; i++) {

if ((*argv[i] == '-') || (*argv[i] == '/')) {

switch (tolower(*(argv[i]+1))) {

case 'p': // protocol sequence

pszProtocolSequence = argv[++i];

break;

case 'e': // endpoint

pszEndpoint = argv[++i];

break;

default:;

}

}

}

if (!StartServiceCtrlDispatcher( DispatchTable)) {

/* Error Handling */

}

}

void WINAPI ServiceStart(DWORD argc, LPTSTR *argv)

{

DWORD status;

DWORD specificError;

ServiceStatus.dwServiceType = SERVICE_WIN32;

ServiceStatus.dwCurrentState = SERVICE_START_PENDING;

ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP |

SERVICE_ACCEPT_PAUSE_CONTINUE;

ServiceStatus.dwWin32ExitCode = 0;

ServiceStatus.dwServiceSpecificExitCode = 0;

ServiceStatus.dwCheckPoint = 0;

ServiceStatus.dwWaitHint = 0;

ServiceStatusHandle = RegisterServiceCtrlHandler(

TEXT("SiTime"),

ServiceCtrlHandler);

if (ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0) {

/* Error Handling */

return;

}

// Initialization code goes here.

status = ServiceInitialization(argc,argv, &specificError);

// Handle error condition

if (status != NO_ERROR) {

ServiceStatus.dwCurrentState = SERVICE_STOPPED;

ServiceStatus.dwCheckPoint = 0;

ServiceStatus.dwWaitHint = 0;

ServiceStatus.dwWin32ExitCode = status;

ServiceStatus.dwServiceSpecificExitCode = specificError;

SetServiceStatus (ServiceStatusHandle, &ServiceStatus);

return;

}

// Initialization complete - report running status

ServiceStatus.dwCurrentState = SERVICE_RUNNING;

ServiceStatus.dwCheckPoint = 0;

ServiceStatus.dwWaitHint = 0;

if (!SetServiceStatus (ServiceStatusHandle, &ServiceStatus)) {

status = GetLastError();

}

// This is where the service does its work. //

ServerProcess();

return;

}

/* stub initialization function */

DWORD ServiceInitialization(DWORD argc, LPTSTR *argv,

DWORD *specificError)

{

*specificError = ServerInit();

if (*specificError) return *specificError;

return(0);

}

void WINAPI ServiceCtrlHandler ( IN DWORD Opcode)

{

DWORD status;

switch(Opcode) {

case SERVICE_CONTROL_PAUSE:

/* Do whatever it takes to pause here. */

ServerDoPause();

ServiceStatus.dwCurrentState = SERVICE_PAUSED;

break;

case SERVICE_CONTROL_CONTINUE:

/* Do whatever it takes to continue here.*/

ServerDoContinue();

ServiceStatus.dwCurrentState = SERVICE_RUNNING;

break;

case SERVICE_CONTROL_STOP:

/* Do whatever it takes to stop here. */

ServerDoStop();

ServiceStatus.dwWin32ExitCode = 0;

ServiceStatus.dwCurrentState = SERVICE_STOPPED;

ServiceStatus.dwCheckPoint = 0;

ServiceStatus.dwWaitHint = 0;

if (!SetServiceStatus (ServiceStatusHandle, &ServiceStatus))

{

status = GetLastError();

}

return;

case SERVICE_CONTROL_INTERROGATE:

/* fall through to send current status */

break;

default:

/* Error handling */

break;

}

/* Send current status.*/

if (!SetServiceStatus (ServiceStatusHandle, &ServiceStatus)) {

status = GetLastError();

}

return;

}

CommonConfig.c

Файл CommonConfig.c - Управление конфигурацией

#include <windows.h>

#include "CommonConfig.h"

#include "EventLog.h"

#define REGVALUENAME_LENGTH 255

DWORD ConfigWatchingThread;

HANDLE hConfigMutex= NULL;

HANDLE hTaskMutex= NULL;

unsigned char * pszProtocolSequence = "ncacn_np";

unsigned char * pszSecurity = NULL;

unsigned char * pszEndpoint = "\\pipe\\CommServ";

unsigned int cMinCalls = 1;

unsigned int cMaxCalls = 20;

unsigned int fDontWait = FALSE;

structTASKENTRY TaskTable[TASK_COUNT];

intEntryCount = 0;

DWORDTaskThreads[TASK_COUNT];

intTaskCount = 0;

void UpdateVariables()

{

HKEYhKey;

DWORDdwIndex = 0;

DWORDVNameLength = REGVALUENAME_LENGTH;

charVName[REGVALUENAME_LENGTH];

DWORDdwLength = sizeof(struct TASKENTRY);

inti;

__try {

WaitForSingleObject(hConfigMutex, INFINITE);

// Инициализация таблицы задач

for (i = 0; i < TASK_COUNT; i++) {

TaskTable[i].Active= FALSE;

TaskTable[i].ExecTime= 0;

ZeroMemory(&TaskTable[i].DllName, sizeof(TaskTable[i].DllName));

TaskTable[i].TermProc= NULL;

TaskTable[i].TaskThread= 0;

}

// Загрузка таблицы задач из реестра

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,

REGISTRY_TASKS_PATH,

0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) {

dwIndex= 0;

EntryCount= 0;

while (RegEnumValue(hKey,

dwIndex,

(char *)&VName,

&VNameLength,

NULL,

NULL,

(LPVOID)&TaskTable[dwIndex],

&dwLength) == ERROR_SUCCESS) {

if (dwLength != sizeof(struct TASKENTRY)) {

LogEvent(EVENTLOG_ERROR_TYPE, "Invalid Task Parameter");

break;

}

EntryCount+=1;

dwIndex+=1;

}

RegCloseKey(hKey);

} else LogEvent(EVENTLOG_ERROR_TYPE, "Error Loading Configuration");

}

__finally {

ReleaseMutex(hConfigMutex);

}

}

DoService.c

#include <windows.h>

#include "DoService.h"

#include "..\Comm.h"

#include "CommonConfig.h"

#include "ClientHandler.h"

#include "EventLog.h"

#include "ShedulerServ.h"

void ServerProcess() {

hConfigMutex = CreateMutex(NULL, FALSE, NULL);

hTaskMutex = CreateMutex(NULL, FALSE, NULL);

CreateThread(NULL, 0, ShedulingProc, NULL, 0, &ShedulingThread);

CreateThread(NULL, 0, RPCClientHandling, NULL, 0, &ClientHandlingThread);

}

DWORD ServerInit() {

RPC_STATUS status;

status = RpcServerUseProtseqEp(

pszProtocolSequence,

cMaxCalls,

pszEndpoint,

pszSecurity); // Security descriptor

if (status != NO_ERROR) {

return(1);

}

status = RpcServerRegisterIf(

CommService_ServerIfHandle, // !!!

NULL, // MgrTypeUuid

NULL); // MgrEpv; null means use default

if (status != NO_ERROR) {

return(2);

}

LogEvent(EVENTLOG_INFORMATION_TYPE, "\"Svyazinform\" Communicatin Service Initialized");

return(0);

}

void ServerDoPause()

{

SuspendThread(&ShedulingThread);

SuspendThread(&ClientHandlingThread);

LogEvent(EVENTLOG_INFORMATION_TYPE, "\"Svyazinform\" Communicatin Service Paused");

}

void ServerDoContinue()

{

ResumeThread(&ShedulingThread);

ResumeThread(&ClientHandlingThread);

LogEvent(EVENTLOG_INFORMATION_TYPE, "\"Svyazinform\" Communicatin Service Resumed");

}

void ServerDoStop() {

RPC_STATUS status;

status = RpcMgmtStopServerListening(NULL);

if (status != NO_ERROR) {

// Error handling

}

status = RpcServerUnregisterIf(NULL, NULL, FALSE);

if (status != NO_ERROR) {

// Error handling

}

TerminateTasks();

WaitForSingleObject(&ClientHandlingThread, 5000);

CloseHandle(&ClientHandlingThread);

InterlockedIncrement(&TerminateSheduling);

WaitForSingleObject(&ShedulingThread, 5000);

CloseHandle(&ShedulingThread);

WaitForSingleObject(hConfigMutex, 3000);

ReleaseMutex(hConfigMutex);

CloseHandle(hConfigMutex);

WaitForSingleObject(hTaskMutex, 3000);

ReleaseMutex(hTaskMutex);

CloseHandle(hTaskMutex);

LogEvent(EVENTLOG_INFORMATION_TYPE, "\"Svyazinform\" Communicatin Service Stopped");

}

/**************************************************************/

/* MIDL allocate and free */

/**************************************************************/

void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len)

{

return(malloc(len));

}

void __RPC_USER midl_user_free(void __RPC_FAR * ptr)

{

free(ptr);

}

ClientHandler.c

/**********************************************************/

/* Этот модуль обрабатывает подключения клиентов */

/**********************************************************/

#include <windows.h>

#include "ClientHandler.h"

#include "CommonConfig.h"

#include "../Comm.h"

DWORDClientHandlingThread;

DWORD WINAPI RPCClientHandling(LPVOID ThreadParm)

{

RPC_STATUS status;

status = RpcServerListen(

cMinCalls,

cMaxCalls,

fDontWait);

if (status != NO_ERROR) {

return 1;

}

return 0;

}

void RefreshIniProps()

{

MessageBeep(1);

return;

}

EventLog.c

#include <windows.h>

#include "EventLog.h"

void LogEvent(WORD EventType, LPSTR EventMsg)

{

HANDLE h;

h = RegisterEventSource(NULL, /* uses local computer */

"CommServ"); /* source name */

if (h != NULL)

{

ReportEvent(h, /* event log handle */

EventType, /* event type */

0, /* category zero */

0x1003, /* event identifier */

NULL, /* no user security identifier */

1, /* one substitution string */

0, /* no data */

&EventMsg, /* address of string array */

NULL); /* address of data */

DeregisterEventSource(h);

}

return;

}

Comm_s.c

/* this ALWAYS GENERATED file contains the RPC server stubs */

/* File created by MIDL compiler version 3.00.15 */

/* at Tue Jun 03 11:35:46 1997

*/

/* Compiler settings for comm.idl:

Os, W1, Zp8, env=Win32, ms_ext, c_ext, oldnames

error checks: none

*/

//@@MIDL_FILE_HEADING( )

#include <string.h>

#include "comm.h"

#define TYPE_FORMAT_STRING_SIZE 1

#define PROC_FORMAT_STRING_SIZE 3

typedef struct _MIDL_TYPE_FORMAT_STRING

{

short Pad;

unsigned char Format[ TYPE_FORMAT_STRING_SIZE ];

} MIDL_TYPE_FORMAT_STRING;

typedef struct _MIDL_PROC_FORMAT_STRING

{

short Pad;

unsigned char Format[ PROC_FORMAT_STRING_SIZE ];

} MIDL_PROC_FORMAT_STRING;

extern const MIDL_TYPE_FORMAT_STRING __MIDLTypeFormatString;

extern const MIDL_PROC_FORMAT_STRING __MIDLProcFormatString;

/* Standard interface: CommService, ver. 1.0,

GUID={0x4a25d2e0,0x6703,0x11d0,{0x89,0x27,0x00,0xa0,0x24,0x13,0x85,0x0e}} */

extern RPC_DISPATCH_TABLE CommService_DispatchTable;

static const RPC_SERVER_INTERFACE CommService___RpcServerInterface =

{

sizeof(RPC_SERVER_INTERFACE),

{{0x4a25d2e0,0x6703,0x11d0,{0x89,0x27,0x00,0xa0,0x24,0x13,0x85,0x0e}},{1,0}},

{{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}},

&CommService_DispatchTable,

0,

0,

0,

0,

0

};

RPC_IF_HANDLE CommService_ServerIfHandle = (RPC_IF_HANDLE)& CommService___RpcServerInterface;

extern const MIDL_STUB_DESC CommService_StubDesc;

void __RPC_STUB

CommService_RefreshIniProps(

PRPC_MESSAGE _pRpcMessage )

{

MIDL_STUB_MESSAGE _StubMsg;

RPC_STATUS _Status;

((void)(_Status));

NdrServerInitializeNew(

_pRpcMessage,

&_StubMsg,

&CommService_StubDesc);

RpcTryFinally

{

RefreshIniProps();

}

RpcFinally

{

}

RpcEndFinally

_pRpcMessage->BufferLength =

(unsigned int)((long)_StubMsg.Buffer - (long)_pRpcMessage->Buffer);

}

static const MIDL_STUB_DESC CommService_StubDesc =

{

(void __RPC_FAR *)& CommService___RpcServerInterface,

MIDL_user_allocate,

MIDL_user_free,

0,

0,

0,

0,

0,

__MIDLTypeFormatString.Format,

0, /* -error bounds_check flag */

0x10001, /* Ndr library version */

0,

0x300000f, /* MIDL Version 3.0.15 */

0,

0,

0, /* Reserved1 */

0, /* Reserved2 */

0, /* Reserved3 */

0, /* Reserved4 */

/* Reserved5 */

};

static RPC_DISPATCH_FUNCTION CommService_table[] =

{

CommService_RefreshIniProps,

0

};

RPC_DISPATCH_TABLE CommService_DispatchTable =

{

1,

CommService_table

};

#if !defined(__RPC_WIN32__)

#error Invalid build platform for this stub.

#endif

static const MIDL_PROC_FORMAT_STRING __MIDLProcFormatString =

{

0,

{

0x5b,/* FC_END */

0x5c,/* FC_PAD */

0x0

}

};

static const MIDL_TYPE_FORMAT_STRING __MIDLTypeFormatString =

{

0,

{

0x0

}

};

ShedulerServ.c

/**********************************************************//* Task Sheduler

/**********************************************************/

#include <windows.h>

#include "ShedulerServ.h"

#include "CommonConfig.h"

#include "EventLog.h"

#define SLEEP_INTERVAL 5000

#define ACTIVATE_INTERVAL 60000

BOOL TerminateSheduling = FALSE;

DWORD ShedulingThread;

DWORD WINAPI TaskProc(LPVOID ThreadParm);

voidAnalyseTaskTable();

DWORDGetTimeInMins();

DWORD WINAPI ShedulingProc(LPVOID ThreadParm)

{

long i = 0;

while (!TerminateSheduling) {

if ((i += SLEEP_INTERVAL) >= ACTIVATE_INTERVAL) {

i = 0;

if (TaskCount == 0)UpdateVariables();

AnalyseTaskTable();

}

Sleep(SLEEP_INTERVAL);

}

return 0;

}

DWORD WINAPI TaskProc(LPVOID ThreadParm)

{

HINSTANCEhLib;

FARPROChProc;

InterlockedIncrement(&TaskCount);

WaitForSingleObject(hConfigMutex, INFINITE);

MessageBeep(1);

if (hLib = LoadLibrary((char *)&((struct TASKENTRY*)ThreadParm)->DllName)) {

if (((struct TASKENTRY*)ThreadParm)->TermProc = GetProcAddress(hLib, (LPCSTR)TaskProcName))

{

((struct TASKENTRY*)ThreadParm)->Active = TRUE;

ReleaseMutex(hConfigMutex);

if (hProc = GetProcAddress(hLib, (LPCSTR)TaskProcName)) {

hProc();

__try {

WaitForSingleObject(hConfigMutex, INFINITE);

((struct TASKENTRY*)ThreadParm)->Active = FALSE;

CloseHandle((HANDLE)((struct TASKENTRY*)ThreadParm)->TaskThread);

}

__finally {

ReleaseMutex(hConfigMutex);

}

} else LogEvent(EVENTLOG_ERROR_TYPE, "Error Getting Procedure Address");

} else LogEvent(EVENTLOG_ERROR_TYPE, "Error Getting TermProc Address");

} else {

ReleaseMutex(hConfigMutex);

LogEvent(EVENTLOG_ERROR_TYPE, "Error Loading Library");

}

InterlockedDecrement(&TaskCount);

return 0;

}

voidAnalyseTaskTable()

{

DWORDCurrTime;

inti;

CurrTime = GetTimeInMins();

__try {

WaitForSingleObject(hConfigMutex, INFINITE);

for (i = 0; i < EntryCount; i++) {

if ((TaskTable[i].ExecTime == CurrTime) &&

(!TaskTable[i].Active)) {

CreateThread(NULL, 0, TaskProc, &TaskTable[i], 0, &TaskTable[i].TaskThread);

}

}

}

__finally {

ReleaseMutex(hConfigMutex);

}

}

DWORDGetTimeInMins()

{

SYSTEMTIME SysTime;

GetLocalTime(&SysTime);

return SysTime.wHour*60+SysTime.wMinute;

}

voidTerminateTasks()

{

inti;

DWORDTaskIndex = 0;

HANDLEHandles[TASK_COUNT];

for (i = 0; i < EntryCount; i++) {

if (TaskTable[i].Active) {

TaskTable[i].TermProc();

Handles[TaskIndex++] = (HANDLE)TaskTable[i].TaskThread;

}

}

WaitForMultipleObjects(TaskIndex, Handles, TRUE, INFINITE);

}

Comm.h

/* this ALWAYS GENERATED file contains the definitions for the interfaces */

/* File created by MIDL compiler version 3.00.15 */

/* at Tue Jun 03 11:35:46 1997

*/

/* Compiler settings for comm.idl:

Os, W1, Zp8, env=Win32, ms_ext, c_ext, oldnames

error checks: none

*/

//@@MIDL_FILE_HEADING( )

#include "rpc.h"

#include "rpcndr.h"

#ifndef __comm_h__

#define __comm_h__

#ifdef __cplusplus

extern "C"{

#endif

/* Forward Declarations */

void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t);

void __RPC_USER MIDL_user_free( void __RPC_FAR * );

#ifndef __CommService_INTERFACE_DEFINED__

#define __CommService_INTERFACE_DEFINED__

/****************************************

Generated header for interface: CommService

at Tue Jun 03 11:35:46 1997

using MIDL 3.00.15

****************************************/

/* [implicit_handle][version][uuid] */

void RefreshIniProps( void);

extern handle_t CommServ_IfHandle;

extern RPC_IF_HANDLE CommService_ClientIfHandle;

extern RPC_IF_HANDLE CommService_ServerIfHandle;

#endif /* __CommService_INTERFACE_DEFINED__ */

/* Additional Prototypes for ALL interfaces */

/* end of Additional Prototypes */

#ifdef __cplusplus

}

#endif

#endif

DoService.h

/**************************************************************/

/* DoService Module - implementation of initialisation other

/* tasks */

/* */

/* Copuright (c) 1997 by Malkov O.V. */

/* JSC "Svyazinform" RM */

/**************************************************************/

#ifndef __DOSERVICE

#define __DESERVICE

void ServerProcess();

DWORD ServerInit();

void ServerDoPause();

void ServerDoStop();

void ServerDoContinue();

#endif

CommonConfig.h

/**************** Server Engine Header File *******************/

#ifndef __COMMON_CONFIG

#define __COMMON_CONFIG

#define TASK_COUNT 10

#include "../RegistryConfig.h"

extern DWORD ConfigWatchingThread;

extern HANDLE hConfigMutex;

extern HANDLE hTaskMutex;

extern unsigned char *pszProtocolSequence;

extern unsigned char *pszSecurity;

extern unsigned char *pszEndpoint;

extern unsigned int cMinCalls;

extern unsigned int cMaxCalls;

extern unsigned int fDontWait;

extern structTASKENTRY TaskTable[TASK_COUNT];

extern intEntryCount;

extern DWORDTaskThreads[TASK_COUNT];

extern intTaskCount;

DWORD WINAPI CommonConfigWatcher(LPVOID ThreadParm);

void UpdateVariables();

#endif

EventLog.h

#ifndef __EVENT_LOG

#define __EVENT_LOG

void LogEvent(WORD EventType, LPSTR EventMsg);

#endif

ClientHandler.h

#ifndef __CLIENT_HANDLER

#define __CLIENT_HANDLER

extern DWORDClientHandlingThread;

DWORD WINAPI RPCClientHandling(LPVOID ThreadParm);

void RefreshIniProps();

#endif

ShedulerServ.h

#ifndef __SHEDULING_SERVICE

#define __SHEDULING_SERVICE

#define TaskProcName "TaskProc"

extern BOOL TerminateSheduling;

extern DWORD ShedulingThread;

DWORD WINAPI ShedulingProc(LPVOID ThreadParm);

voidTerminateTasks();

#endif

RegistryConfig.h

#ifndef __REGISTRY_CONFIG

#define __REGISTRY_CONFIG

#define REGISTRY_TASKS_PATH "SOFTWARE\\Svyazinform\\CommService\\Tasks"

struct TASKENTRY

{

DWORDExecTime;

charDllName[256];

FARPROCTermProc;

DWORDTaskThread;

BOOLActive;

};

#endif

Comm.idl

/* IDL File */

[ uuid (4a25d2e0-6703-11d0-8927-00a02413850e),

version(1.0)

]

interface CommService

{

void RefreshIniProps();

}

Comm.acf

/* acf file for TimeInclude Service (RPC) */

[ implicit_handle(handle_t CommServ_IfHandle)

]interface CommService

{

}

Приложение 4

Исходные тексты программы установки коммуникационного сервиса

#include <windows.h>

#include <stdio.h>

void RegEventSource();

VOID _CRTAPI1 main(void)

{

LPCTSTR lpszBinaryPathName =

TEXT("c:\\ibserver\\bin\\CommServ.exe");

SC_HANDLE schSCManager;

SC_HANDLE schService;

/* Open a handle to the SC Manager database. */

schSCManager = OpenSCManager(

NULL, /* local machine */

NULL, /* ServicesActive database */

SC_MANAGER_ALL_ACCESS); /* full access rights */

if (schSCManager == NULL) {

printf("\nError opening Service Manager.\n");

return;

}

schService = CreateService(

schSCManager, /* SCManager database */

TEXT("CommServ"), /* name of service */

TEXT("JSC \"SvjazInform\" Communication Service"), /* service name to display */

SERVICE_ALL_ACCESS, /* desired access */

SERVICE_WIN32_OWN_PROCESS, /* service type */

SERVICE_DEMAND_START, /* start type */

SERVICE_ERROR_NORMAL, /* error control type */

lpszBinaryPathName, /* service's binary */

NULL, /* no load ordering group */

NULL, /* no tag identifier */

NULL, /* no dependencies */

NULL, /* LocalSystem account */

NULL); /* no password */

if (schService == NULL) {

printf("\nFailed to create service!\n");

}

else

printf("CreateService SUCCESS\n");

CloseServiceHandle(schService);

CloseServiceHandle(schSCManager);

RegEventSource();

}

void RegEventSource()

{

HKEY hk;

DWORD dwData;

UCHAR szBuf[80];

if (RegCreateKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\

\\EventLog\\Application\\CommServ", &hk)) {

printf("could not create registry key");

return;

}

/* Set the Event ID message-file name. */

strcpy(szBuf, "c:\\ibserver\\bin\\CommServ.exe");

/* Add the Event ID message-file name to the subkey. */

if (RegSetValueEx(hk, /* subkey handle */

"EventMessageFile", /* value name */

0, /* must be zero */

REG_EXPAND_SZ, /* value type */

(LPBYTE) szBuf, /* address of value data */

strlen(szBuf) + 1)) /* length of value data*/

{

printf("could not set event message file");

return;

}

/* Set the supported types flags. */

dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |EVENTLOG_INFORMATION_TYPE;

if (RegSetValueEx(hk, /* subkey handle */

"TypesSupported", /* value name */

0, /* must be zero */

REG_DWORD, /* value type */

(LPBYTE) &dwData, /* address of value data*/

sizeof(DWORD))) /* length of value data */

{

printf("could not set supported types");

return;

}

RegCloseKey(hk);

}

Приложение 5

Исходные тексты программы удаления коммуникационного сервиса

#include <windows.h>

#include <stdio.h>

void CleanRegistry();

VOID _CRTAPI1 main(void)

{

SC_HANDLE schSCManager;

SC_HANDLE schService;

/* Open a handle to the SC Manager database. */

schSCManager = OpenSCManager(

NULL, /* local machine */

NULL, /* ServicesActive database */

SC_MANAGER_ALL_ACCESS); /* full access rights */

if (schSCManager == NULL) {

printf("\nError opening Service Manager.\n");

return;

}

schService = OpenService(

schSCManager, /* SCManager database */

TEXT("CommServ"), /* name of service */

DELETE); /* only need DELETE access */

if (! DeleteService(schService) )

printf("\nFailed to Delete service!\n");

else

printf("DeleteService SUCCESS\n");

CloseServiceHandle(schService);

CloseServiceHandle(schSCManager);

}

void CleanRegistry()

{

if (RegDeleteKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\

\\EventLog\\Application\\CommServ"))

{

printf("\nError Cleaning Registry");

} else {

printf("\nCleaning Registry SUCCESS");

}

return;

}

Размещено на Allbest.ru


Подобные документы

  • Модели информационного процесса обработки данных. Классификация баз данных. Сеть архитектуры и технология клиент-сервер. Создание запросов к реляционным базам данных на SQL. Работа с электронными таблицами MS Excel: форматирование данных, вычисления.

    контрольная работа [17,8 K], добавлен 17.01.2010

  • Определение базы данных и банков данных. Компоненты банка данных. Основные требования к технологии интегрированного хранения и обработки данных. Система управления и модели организации доступа к базам данных. Разработка приложений и администрирование.

    презентация [17,1 K], добавлен 19.08.2013

  • Обработка распределенных данных и запросов. Многопотоковые и многосерверные архитектуры. Основные типы параллелелизма при обработке запросов. Структура компонентов поддержки удаленного доступа. Доступ к базам данных в двухзвенных моделях клиент-сервер.

    презентация [123,1 K], добавлен 19.08.2013

  • Определение понятия CASE-технологий. Использование комплексного инструментария ER/Studio для создания логической и физической модели данных, генерирования баз данных на платформе СУБД Access. Процедура добавления атрибутов и сущностей, создания связей.

    контрольная работа [2,2 M], добавлен 21.12.2011

  • Основные объекты СУБД Microsoft Access. Формирование запросов на выборку. Основные протоколы обмена в компьютерных сетях. Использование и применение архитектуры клиент-сервер или файл-сервер. Основы реляционных БД. Наиболее известные модели данных.

    курсовая работа [1,3 M], добавлен 13.01.2014

  • Основные понятия и классификация систем управления базами данных. Модели организации данных. Проектирование реляционных баз данных. Основные особенности создания и использования баз данных для информационного обеспечения управленческой деятельности.

    курсовая работа [2,0 M], добавлен 20.01.2013

  • Представление данных в памяти компьютера. Обобщенные структуры и модели данных. Методы доступа к информации. Физическая организация системы управления базами данных, структура сервера. Архитектура "клиент-сервер". Создание базы данных с помощью "Денвер".

    курсовая работа [770,3 K], добавлен 17.11.2014

  • Преимущества распределенных система обработки данных. Классификация интегрированных технологий. Модели реализации технологии "клиент-сервер". Мониторы обработки транзакций. Глобальные вычислительные и информационные сети. Виды доступа к глобальным сетям.

    презентация [2,1 M], добавлен 20.11.2013

  • Изучение особенностей информационного процесса обработки данных. Процессы, связанные с поиском, хранением, передачей, обработкой и использованием информации. Основные режимы обработки данных на ЭВМ. Организация обслуживания вычислительных задач.

    реферат [130,9 K], добавлен 28.09.2014

  • Проблема применения методов прогнозирования кадровой работы на основе использования компьютерных технологий. Концепция банка данных, сущность и функции. Отличие реляционных и объектно-ориентированных баз данных. Организация и технология обработки данных.

    реферат [1,0 M], добавлен 23.09.2014

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.