Beispiel #1
0
void CFrameWnd::SetMessageText( UINT nID )
/****************************************/
{
    CString str;
    GetMessageString( nID, str );
    SetMessageText( str );
}
Beispiel #2
0
LRESULT COleIPFrameWnd::OnSetMessageString(WPARAM wParam, LPARAM lParam)
{
	USES_CONVERSION;

	if (m_lpFrame != NULL)
	{
		LPCTSTR lpsz = NULL;
		CString strMessage;

		// set the message bar text
		if (lParam != NULL)
		{
			ASSERT(wParam == 0);    // can't have both an ID and a string
			lpsz = (LPCTSTR)lParam; // set an explicit string
		}
		else if (wParam != 0)
		{
			// get message associated with the ID indicated by wParam
			GetMessageString(wParam, strMessage);
			lpsz = strMessage;
		}

		// notify container of new status text
		if (lpsz == NULL)
			lpsz = &afxChNil;
		m_lpFrame->SetStatusText(T2COLE(lpsz));
	}

	UINT nIDLast = m_nIDLastMessage;
	m_nIDLastMessage = (UINT)wParam;    // new ID (or 0)
	m_nIDTracking = (UINT)wParam;       // so F1 on toolbar buttons work
	return nIDLast;
}
BOOL CAddSubmtDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	if (!m_bAdd) {
		SetWindowText(GetMessageString(IDS_EDIT_PATH_NAME));
		((CEdit *)GetDlgItem(IDC_SHARE_NAME))->EnableWindow(FALSE);
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
Beispiel #4
0
// If the message string contains parameter insertion strings (for example, %%4096),
// you must perform the parameter substitution yourself. To get the parameter message 
// string, call FormatMessage with the message identifier found in the parameter insertion 
// string (for example, 4096 is the message identifier if the parameter insertion string
// is %%4096). You then substitute the parameter insertion string in the message 
// string with the actual parameter message string. 
//
// In this example, the message string for message ID 0x103 is "%1 %%4096 = %2 %%4097.".
// When you call FormatMessage to get the message string, FormatMessage returns 
// "8 %4096 = 2 %4097.". You need to replace %4096 and %4097 with the message strings
// associated with message IDs 4096 and 4097, respectively.
static DWORD ApplyParameterStringsToMessage(CONST LPCWSTR pMessage, LPWSTR & pFinalMessage)
{
	DWORD status = ERROR_SUCCESS;
	DWORD dwParameterCount = 0;  // Number of insertion strings found in pMessage
	size_t cbBuffer = 0;         // Size of the buffer in bytes
	size_t cchBuffer = 0;        // Size of the buffer in characters
	size_t cchParameters = 0;    // Number of characters in all the parameter strings
	size_t cch = 0;
	DWORD i = 0;
	LPWSTR* pStartingAddresses = NULL;  // Array of pointers to the beginning of each parameter string in pMessage
	LPWSTR* pEndingAddresses = NULL;    // Array of pointers to the end of each parameter string in pMessage
	DWORD* pParameterIDs = NULL;        // Array of parameter identifiers found in pMessage
	LPWSTR* pParameters = NULL;         // Array of the actual parameter strings
	LPWSTR pTempMessage = (LPWSTR)pMessage;
	LPWSTR pTempFinalMessage = NULL;

	// Determine the number of parameter insertion strings in pMessage.
	while (pTempMessage = wcschr(pTempMessage, L'%'))
	{
		dwParameterCount++;
		pTempMessage++;
	}

	// If there are no parameter insertion strings in pMessage, return.
	if (0 == dwParameterCount)
	{
		pFinalMessage = NULL;
		goto cleanup;
	}

	// Allocate an array of pointers that will contain the beginning address 
	// of each parameter insertion string.
	cbBuffer = sizeof(LPWSTR) * dwParameterCount;
	pStartingAddresses = (LPWSTR*)malloc(cbBuffer);
	if (NULL == pStartingAddresses)
	{
		wprintf(L"Failed to allocate memory for pStartingAddresses.\n");
		status = ERROR_OUTOFMEMORY;
		goto cleanup;
	}

	RtlZeroMemory(pStartingAddresses, cbBuffer);

	// Allocate an array of pointers that will contain the ending address (one
	// character past the of the identifier) of the each parameter insertion string.
	pEndingAddresses = (LPWSTR*)malloc(cbBuffer);
	if (NULL == pEndingAddresses)
	{
		wprintf(L"Failed to allocate memory for pEndingAddresses.\n");
		status = ERROR_OUTOFMEMORY;
		goto cleanup;
	}

	RtlZeroMemory(pEndingAddresses, cbBuffer);

	// Allocate an array of pointers that will contain pointers to the actual
	// parameter strings.
	pParameters = (LPWSTR*)malloc(cbBuffer);
	if (NULL == pParameters)
	{
		wprintf(L"Failed to allocate memory for pEndingAddresses.\n");
		status = ERROR_OUTOFMEMORY;
		goto cleanup;
	}

	RtlZeroMemory(pParameters, cbBuffer);

	// Allocate an array of DWORDs that will contain the message identifier
	// for each parameter.
	pParameterIDs = (DWORD*)malloc(cbBuffer);
	if (NULL == pParameterIDs)
	{
		wprintf(L"Failed to allocate memory for pParameterIDs.\n");
		status = ERROR_OUTOFMEMORY;
		goto cleanup;
	}

	RtlZeroMemory(pParameterIDs, cbBuffer);

	// Find each parameter in pMessage and get the pointer to the
	// beginning of the insertion string, the end of the insertion string,
	// and the message identifier of the parameter.
	pTempMessage = (LPWSTR)pMessage;
	while (pTempMessage = wcschr(pTempMessage, L'%'))
	{
		if (isdigit(*(pTempMessage+1)))
		{
			pStartingAddresses[i] = pTempMessage;

			pTempMessage++;
			pParameterIDs[i] = (DWORD)_wtoi(pTempMessage);

			while (isdigit(*++pTempMessage))
				;

			pEndingAddresses[i] = pTempMessage;

			i++;
		}
	}

	// For each parameter, use the message identifier to get the
	// actual parameter string.
	for (DWORD i = 0; i < dwParameterCount; i++)
	{
		pParameters[i] = GetMessageString(pParameterIDs[i], 0, NULL);
		if (NULL == pParameters[i])
		{
			wprintf(L"GetMessageString could not find parameter string for insert %lu.\n", i);
			status = ERROR_INVALID_PARAMETER;
			goto cleanup;
		}

		cchParameters += wcslen(pParameters[i]);
	}

	// Allocate enough memory for pFinalMessage based on the length of pMessage
	// and the length of each parameter string. The pFinalMessage buffer will contain 
	// the completed parameter substitution.
	pTempMessage = (LPWSTR)pMessage;
	cbBuffer = (wcslen(pMessage) + cchParameters + 1) * sizeof(WCHAR);
	pFinalMessage = (LPWSTR)malloc(cbBuffer);
	if (NULL == pFinalMessage)
	{
		wprintf(L"Failed to allocate memory for pFinalMessage.\n");
		status = ERROR_OUTOFMEMORY;
		goto cleanup;
	}

	RtlZeroMemory(pFinalMessage, cbBuffer);
	cchBuffer = cbBuffer / sizeof(WCHAR);
	pTempFinalMessage = pFinalMessage;

	// Build the final message string.
	for (DWORD i = 0; i < dwParameterCount; i++)
	{
		// Append the segment from pMessage. In the first iteration, this is "8 " and in the
		// second iteration, this is " = 2 ".
		wcsncpy_s(pTempFinalMessage, cchBuffer, pTempMessage, cch = (pStartingAddresses[i] - pTempMessage));
		pTempMessage = pEndingAddresses[i];
		cchBuffer -= cch;

		// Append the parameter string. In the first iteration, this is "quarts" and in the
		// second iteration, this is "gallons"
		pTempFinalMessage += cch;
		wcscpy_s(pTempFinalMessage, cchBuffer, pParameters[i]);
		cchBuffer -= cch = wcslen(pParameters[i]);

		pTempFinalMessage += cch;
	}

	// Append the last segment from pMessage, which in this example is ".".
	wcscpy_s(pTempFinalMessage, cchBuffer, pTempMessage);

cleanup:

	if (ERROR_SUCCESS != status)
		pFinalMessage = (LPWSTR)pMessage;

	if (pStartingAddresses)
		free(pStartingAddresses);

	if (pEndingAddresses)
		free(pEndingAddresses);

	if (pParameterIDs)
		free(pParameterIDs);

	for (DWORD i = 0; i < dwParameterCount; i++)
	{
		if (pParameters[i])
			LocalFree(pParameters[i]);
	}

	return status;
}
Beispiel #5
0
// Write the contents of each event record that was written to the log since
// the last notification. The service signals the event object every five seconds
// if an event has been written to the log.
static DWORD DumpNewRecords(int index)
{
	DWORD status = ERROR_SUCCESS;
	DWORD dwLastRecordNumber = 0;
	LPWSTR pMessage = NULL;
	LPWSTR pFinalMessage = NULL;
	PBYTE pRecord = NULL;

	HANDLE hEventLog = g_arrhEventLog[index];

	// Read the first record to prime the loop.
	status = ReadRecord(hEventLog, pRecord, 0, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_FORWARDS_READ);
	if (ERROR_SUCCESS != status && ERROR_HANDLE_EOF != status)
	{
		wprintf(L"ReadRecord (priming read) failed.\n");
		goto cleanup;
	}

	// During the five second notification period, one or more records could
	// have been written to the log. Read all the records that have been 
	// written since the last notification. 
	int nMonSize = sizeof(event_monitor)/sizeof(struct _EVENT_MONITOR);
	while (ERROR_HANDLE_EOF != status)
	{
		int i = 0;
		for (; i<nMonSize; i++)
		{
			if (0 == wcscmp(event_monitor[i].provider_name, (LPWSTR)(pRecord + sizeof(EVENTLOGRECORD))))
			{
				break;
			}
		}

		// If the event was written by our provider, write the contents of the event.
		//if (0 == wcscmp(PROVIDER_NAME, (LPWSTR)(pRecord + sizeof(EVENTLOGRECORD))))
		if (i<nMonSize)
		{
			g_hResources = event_monitor[i].hResource;

			wprintf(L"record number: %lu\n", ((PEVENTLOGRECORD)pRecord)->RecordNumber);
			wprintf(L"status code: %d\n", ((PEVENTLOGRECORD)pRecord)->EventID & 0xFFFF);
			wprintf(L"event type: %s\n", pEventTypeNames[GetEventTypeName(((PEVENTLOGRECORD)pRecord)->EventType)]);

			pMessage = GetMessageString(((PEVENTLOGRECORD)pRecord)->EventCategory, 0, NULL);

			if (pMessage)
			{
				wprintf(L"event category: %s", pMessage);
				LocalFree(pMessage);
				pMessage = NULL;
			}

			pMessage = GetMessageString(((PEVENTLOGRECORD)pRecord)->EventID, 
				((PEVENTLOGRECORD)pRecord)->NumStrings, (LPWSTR)(pRecord + ((PEVENTLOGRECORD)pRecord)->StringOffset));

			if (pMessage)
			{
				status = ApplyParameterStringsToMessage(pMessage, pFinalMessage);

				wprintf(L"event message: %s", (pFinalMessage) ? pFinalMessage : pMessage);

				if (event_monitor[i].FuncEventProcess)
				{
					event_monitor[i].FuncEventProcess((pFinalMessage) ? pFinalMessage : pMessage,	GetEventTypeName(((PEVENTLOGRECORD)pRecord)->EventType));
				}


				LocalFree(pMessage);
				pMessage = NULL;

				if (pFinalMessage)
				{
					free(pFinalMessage);
					pFinalMessage = NULL;
				}
			}

			// To write the event data, you need to know the format of the data. In
			// this example, we know that the event data is a null-terminated string.
			if (((PEVENTLOGRECORD)pRecord)->DataLength > 0)
			{
				wprintf(L"event data: %s\n", (LPWSTR)(pRecord + ((PEVENTLOGRECORD)pRecord)->DataOffset));
			}

			wprintf(L"\n");
		}

		// Read sequentially through the records.
		status = ReadRecord(hEventLog, pRecord, 0, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_FORWARDS_READ);
		if (ERROR_SUCCESS != status && ERROR_HANDLE_EOF != status)
		{
			wprintf(L"ReadRecord sequential failed.\n");
			goto cleanup;
		}
	}

	if (ERROR_HANDLE_EOF == status)
	{
		status = ERROR_SUCCESS;
	}

cleanup:

	if (pRecord)
		free(pRecord);

	return status;
}
Beispiel #6
0
/////////////////////////////////////////////////////////////////////////////
// IConextMenu Functions
/////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CShellExt::XMenuExt::QueryContextMenu(HMENU hMenu,UINT indexMenu,
						   UINT idCmdFirst, UINT idCmdLast,UINT uFlags)
{
    METHOD_PROLOGUE(CShellExt, MenuExt);

    // Don't add any menu items if we're being asked to deal with this file as a shortcut.
    if (uFlags & CMF_VERBSONLY)
	return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, (USHORT)0);

    if (!pThis->m_bIsPathInAFS)
	return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, (USHORT)0);

    // Check to see if there's already an AFS menu here; if so, remove it
    int nItemsNow = GetMenuItemCount (hMenu);
    CString strAfsItemText = GetMessageString(IDS_AFS_ITEM);
    CString strDeleteText = GetMessageString(IDS_MENU_DELETE);
    CString strCutText = GetMessageString(IDS_MENU_CUT);
    LPCTSTR pszAfsItemText = (LPCTSTR)strAfsItemText;
    for (int iItem = 0; iItem < nItemsNow; iItem++) {
	TCHAR szItemText[256];
	if (!GetMenuString (hMenu, iItem, szItemText, 256, MF_BYPOSITION))
	    continue;
	if (lstrcmp (szItemText, pszAfsItemText)==0) {
	    DeleteMenu (hMenu, iItem, MF_BYPOSITION);
	    continue;
	}
	if (((lstrcmp(szItemText,strDeleteText)==0)||(lstrcmp(szItemText,strCutText)==0))&&((pThis->m_bIsSymlink)||(pThis->m_bIsMountpoint))) {
        DeleteMenu (hMenu, iItem, MF_BYPOSITION);
	    continue;
	}
    }
    int indexShellMenu = 0;

    // Create the AFS submenu using the allowed ID's.
    HMENU hAfsMenu = CreatePopupMenu();
    int indexAfsMenu = 0;

    // Only enable the ACL menu item if a single directory is selected
    int nSingleDirOnly = MF_GRAYED;
    if (pThis->m_bDirSelected && (pThis->m_astrFileNames.GetSize() == 1))
	nSingleDirOnly = MF_ENABLED;
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION | nSingleDirOnly, idCmdFirst + IDM_ACL_SET, GetMessageString(IDS_ACLS_ITEM));

    // Volume/Partition submenu of the AFS submenu
    HMENU hVolPartMenu = CreatePopupMenu();
    int indexVolPartMenu = 0;
    ::InsertMenu(hVolPartMenu, indexVolPartMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_VOLUME_PROPERTIES, GetMessageString(IDS_VOL_PART_PROPS_ITEM));
    ::InsertMenu(hVolPartMenu, indexVolPartMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_VOLUMEPARTITION_UPDATENAMEIDTABLE, GetMessageString(IDS_VOL_PART_REFRESH_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION | MF_POPUP, (UINT)hVolPartMenu, GetMessageString(IDS_VOL_PART_ITEM));

    // Mount Point submenu of the AFS submenu
    HMENU hMountPointMenu = CreatePopupMenu();
    int indexMountPointMenu = 0;
    int nMountPointSelected = MF_GRAYED;
    for (int n = pThis->m_astrFileNames.GetSize() - 1 ; n >= 0; n--) {
	if ( IsMountPoint(pThis->m_astrFileNames[n]) ) {
	    nMountPointSelected = MF_ENABLED;
	    break;
	}
    }
    ::InsertMenu(hMountPointMenu, indexMountPointMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_MOUNTPOINT_SHOW, GetMessageString(IDS_MP_SHOW_ITEM));
    ::InsertMenu(hMountPointMenu, indexMountPointMenu++, MF_STRING | MF_BYPOSITION | nMountPointSelected, idCmdFirst + IDM_MOUNTPOINT_REMOVE, GetMessageString(IDS_MP_REMOVE_ITEM));
    ::InsertMenu(hMountPointMenu, indexMountPointMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_MOUNTPOINT_MAKE, GetMessageString(IDS_MP_MAKE_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION | MF_POPUP, (UINT)hMountPointMenu, GetMessageString(IDS_MOUNT_POINT_ITEM));

    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_FLUSH, GetMessageString(IDS_FLUSH_FILE_DIR_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_FLUSH_VOLUME, GetMessageString(IDS_FLUSH_VOLUME_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_SHOW_SERVER, GetMessageString(IDS_SHOW_FILE_SERVERS_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_SHOWCELL, GetMessageString(IDS_SHOW_CELL_ITEM));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_SERVER_STATUS, GetMessageString(IDS_SHOW_SERVER_STATUS_ITEM));

    HMENU hSymbolicMenu = CreatePopupMenu();
    int indexSymbolicMenu = 0;
    int nSymlinkSelected = MF_GRAYED;
    for (int n = pThis->m_astrFileNames.GetSize() - 1 ; n >= 0; n--) {
	if ( IsSymlink(pThis->m_astrFileNames[n]) ) {
	    nSymlinkSelected = MF_ENABLED;
	    break;
	}
    }

    ::InsertMenu(hSymbolicMenu, indexSymbolicMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_SYMBOLICLINK_ADD, GetMessageString(IDS_SYMBOLICLINK_ADD));
    ::InsertMenu(hSymbolicMenu, indexSymbolicMenu++, MF_STRING | MF_BYPOSITION | nSymlinkSelected, idCmdFirst + IDM_SYMBOLICLINK_SHOW, GetMessageString(IDS_SYMBOLICLINK_SHOW));
    ::InsertMenu(hSymbolicMenu, indexSymbolicMenu++, MF_STRING | MF_BYPOSITION | nSymlinkSelected, idCmdFirst + IDM_SYMBOLICLINK_REMOVE, GetMessageString(IDS_SYMBOLICLINK_REMOVE));
    ::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION | MF_POPUP, (UINT)hSymbolicMenu, GetMessageString(IDS_SYMBOLIC_LINK_ITEM));

    // The Submounts menu has been removed because the AFS tray icon
    // and control panel now support mapping drives directly to an AFS
    // path.
    //
    //HMENU hSubmountMenu = CreatePopupMenu();
    //int indexSubmountMenu = 0;
    //::InsertMenu(hSubmountMenu, indexSubmountMenu++, MF_STRING | MF_BYPOSITION | nSingleDirOnly, idCmdFirst + IDM_SUBMOUNTS_CREATE, GetMessageString(IDS_SUBMOUNTS_CREATE_ITEM));
    //::InsertMenu(hSubmountMenu, indexSubmountMenu++, MF_STRING | MF_BYPOSITION, idCmdFirst + IDM_SUBMOUNTS_EDIT, GetMessageString(IDS_SUBMOUNTS_EDIT_ITEM));
    //::InsertMenu(hAfsMenu, indexAfsMenu++, MF_STRING | MF_BYPOSITION | MF_POPUP, (UINT)hSubmountMenu, GetMessageString(IDS_SUBMOUNTS_ITEM));

    // Add a separator
    ::InsertMenu (hMenu, indexMenu + indexShellMenu++, MF_STRING | MF_BYPOSITION | MF_SEPARATOR, 0, TEXT(""));

    // Add the AFS submenu to the shell's menu
    ::InsertMenu(hMenu, indexMenu + indexShellMenu++, MF_STRING | MF_BYPOSITION | MF_POPUP, (UINT)hAfsMenu, GetMessageString(IDS_AFS_ITEM));

    // Add a separator after us
    ::InsertMenu (hMenu, indexMenu + indexShellMenu++, MF_STRING | MF_BYPOSITION | MF_SEPARATOR, 0, TEXT(""));

    return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL,
			 (USHORT)indexAfsMenu + indexVolPartMenu + indexMountPointMenu + indexShellMenu + indexSymbolicMenu);
}
/**
 *	@brief	Generates a message string about DialogLayoutException.
 *	@retval	true	processed.
 *	@retval	false	not processed.
 */
bool ExceptionMessageGenerator::processDialogLayoutException(Exception* ex, MBCString& message) const
{
	DialogLayoutException* myException = dynamic_cast<DialogLayoutException*>(ex);
	if (NULL == myException)
	{
		return false;
	}

	bool resolved = false;

	// DialogLayoutExceptions::FailedToCompute
	if (!resolved)
	{
		DialogLayoutExceptions::FailedToCompute* myExceptionFTC = dynamic_cast<DialogLayoutExceptions::FailedToCompute*>(ex);
		if (NULL != myExceptionFTC)
		{
			ConstAStr arrow = ALITERAL(" -> ");
			MBCString leafMessage;
			MBCString itemName = myExceptionFTC->GetItemName();
			MBCString itemRefPath;
			MBCString itemRefPathLine = itemName;
			Exception* iex = myExceptionFTC->GetInnerException();
			while (NULL != iex)
			{
				DialogLayoutExceptions::FailedToCompute* ftcInner = dynamic_cast<DialogLayoutExceptions::FailedToCompute*>(iex);
				if (NULL != ftcInner)
				{
					itemRefPathLine += arrow;
					MBCString innerItemName = ftcInner->GetItemName();
					if (itemRefPathLine.Length() + innerItemName.Length() >= 80)
					{
						itemRefPath += itemRefPathLine;
						itemRefPathLine = ALITERAL("\n  ");
					}
					itemRefPathLine += innerItemName;
					iex = ftcInner->GetInnerException();
				}
				else
				{
					GetMessageString(iex, leafMessage);
					break;
				}
			}

			itemRefPath += itemRefPathLine;
			MessageFormatter::Format(message, stringLoader->LoadNativeString(NSID_EMSG_DIALOG_LAYOUT_COMPUTE), itemName.CString(), leafMessage.CString(), itemRefPath.CString());
			resolved = true;
		}
	}

	// DialogLayoutExceptions::ItemNotFound
	if (!resolved)
	{
		DialogLayoutExceptions::ItemNotFound* myExceptionINF = dynamic_cast<DialogLayoutExceptions::ItemNotFound*>(ex);
		if (NULL != myExceptionINF)
		{
			MessageFormatter::Format(message, stringLoader->LoadNativeString(NSID_EMSG_DIALOG_LAYOUT_NOT_FOUND), myExceptionINF->GetItemName().CString());
			resolved = true;
		}
	}

	// DialogLayoutExceptions::CircularReference
	if (!resolved)
	{
		DialogLayoutExceptions::CircularReference* myExceptionCR = dynamic_cast<DialogLayoutExceptions::CircularReference*>(ex);
		if (NULL != myExceptionCR)
		{
			message = stringLoader->LoadNativeString(NSID_EMSG_DIALOG_LAYOUT_CIRCULAR_REF);
			resolved = true;
		}
	}

	// DialogLayoutExceptions::ItemNotComputed
	if (!resolved)
	{
		// This must be a bug of the application. It must not be occured in end-user environment.
	}

	return true;
}
Beispiel #8
0
/* Process a given event */
DWORD ProcessEvent(EVT_HANDLE hEvent)
{
    EVT_HANDLE hProviderMetadata = NULL;
	PEVT_VARIANT eventInfo = NULL;
    LPWSTR pwsMessage = NULL;
    LPWSTR pwszPublisherName = NULL;
	ULONGLONG eventTime;
	ULONGLONG keyword;
    DWORD status = ERROR_SUCCESS;
	int event_id = 0;
	int winlevel = 0;
	int level = 0;

	WCHAR source[SOURCE_SZ];
	WCHAR hostname[HOSTNAME_SZ];
	WCHAR * formatted_string = NULL;
	WCHAR * tstamp = NULL;
	WCHAR * index = NULL;
	WCHAR defmsg[ERRMSG_SZ];
	WCHAR tstamped_message[SYSLOG_DEF_SZ];

    /* Get and store the publishers new Windows Events name */
	eventInfo = GetEventInfo(hEvent);
	if (eventInfo) {
		pwszPublisherName = (LPWSTR)eventInfo[0].StringVal;
	}
	else {
		return ERR_CONTINUE;
	}
	eventTime = eventInfo[1].FileTimeVal;
	event_id = eventInfo[2].UInt16Val;

	/* Check for the "Microsoft-Windows-" prefix in the publisher name */
	/* and remove it if found. Saves 18 characters in the message */
	if(wcsncmp(pwszPublisherName, L"Microsoft-Windows-", 18) == 0)
		wcsncpy_s(source, COUNT_OF(source), pwszPublisherName+18, _TRUNCATE);
	else
		wcsncpy_s(source, COUNT_OF(source), pwszPublisherName, _TRUNCATE);

	/* Format Event Timestamp */
	if ((tstamp = WinEventTimeToString(eventTime)) == NULL)
		tstamp = L"TIME_ERROR";

	/* Add hostname for RFC compliance (RFC 3164) */
	if (ProgramUseIPAddress == TRUE) {
		_snwprintf_s(hostname, HOSTNAME_SZ, _TRUNCATE, L"%S", ProgramHostName);
	} else {
		if (ExpandEnvironmentStringsW(L"%COMPUTERNAME%", hostname, COUNT_OF(hostname)) == 0) {
			wcscpy_s(hostname, COUNT_OF(hostname), L"HOSTNAME_ERR");
			Log(LOG_ERROR|LOG_SYS, "Cannot expand %COMPUTERNAME%");
		}
    }

	/* replace every space in source by underscores */
	index = source;
	while( *index ) {
		if( *index == L' ' ) {
			*index = L'_';
		}
		index++;
	}

	/* Add Timestamp and hostname then format source & event ID for consistency with Event Viewer */
    if(SyslogIncludeTag)
    {
        _snwprintf_s(tstamped_message, COUNT_OF(tstamped_message), _TRUNCATE, L"%s %s %S: %s: %i: ",
            tstamp,
            hostname,
            SyslogTag,
            source,
            event_id
        );
    }
    else
    {
        _snwprintf_s(tstamped_message, COUNT_OF(tstamped_message), _TRUNCATE, L"%s %s %s: %i: ",
            tstamp,
            hostname,
            source,
            event_id
        );
    }

	/* Get the handle to the provider's metadata that contains the message strings. */
	hProviderMetadata = EvtOpenPublisherMetadata(NULL, pwszPublisherName, NULL, 0, 0);
	if (NULL == hProviderMetadata) {
		if (LogInteractive)
			Log(LOG_ERROR|LOG_SYS, "OpenPublisherMetadata failed for Publisher: \"%S\"", source);
		return ERR_CONTINUE;
	}

	/* Get the message string from the event */
	pwsMessage = GetMessageString(hProviderMetadata, hEvent);
	if (pwsMessage == NULL) {
		Log(LOG_ERROR|LOG_SYS, "Error getting message string for event DETAILS: Publisher: %S EventID: %i", source, event_id);
		return ERR_CONTINUE;
	}

	/* Get string and strip whitespace */
	formatted_string = CollapseExpandMessageW(pwsMessage);

	/* Create a default message if resources or formatting didn't work */
	if (formatted_string == NULL) {
        if(SyslogIncludeTag)
        {
		    _snwprintf_s(defmsg, COUNT_OF(defmsg), _TRUNCATE,
                L"%S: (Facility: %u, Status: %s)",
                SyslogTag,
			    HRESULT_FACILITY(event_id),
			    FAILED(event_id) ? L"Failure" : L"Success"
		    );
        }
        else
        {
            _snwprintf_s(defmsg, COUNT_OF(defmsg), _TRUNCATE,
                L"(Facility: %u, Status: %s)",
			    HRESULT_FACILITY(event_id),
			    FAILED(event_id) ? L"Failure" : L"Success"
		    );
        }
		formatted_string = defmsg;
	}

	/* Get Event Error Level. In the case of Security Events,
	 * set Failures to Error instead of notice using the
	 * keyword attribute
	 */
	keyword = (EvtVarTypeNull == eventInfo[4].Type) ? 0 : eventInfo[4].UInt64Val;
	if ((keyword & WINEVENT_KEYWORD_AUDIT_FAILURE) != 0) {
        // Add AUDIT_FAILURE message for better parsing
        wcsncat_s(tstamped_message, COUNT_OF(tstamped_message), L"AUDIT_FAILURE ", _TRUNCATE);
		winlevel = WINEVENT_ERROR_LEVEL;
    }
	else
		winlevel = (int)eventInfo[3].ByteVal;

	/* Select syslog level */
	switch (winlevel) {
		case WINEVENT_CRITICAL_LEVEL:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_CRIT);
			break;		
		case WINEVENT_ERROR_LEVEL:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_ERR);
			break;
		case WINEVENT_WARNING_LEVEL:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_WARNING);
			break;
		case WINEVENT_INFORMATION_LEVEL:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_NOTICE);
			break;
		case WINEVENT_AUDIT_LEVEL:
            wcsncat_s(tstamped_message, COUNT_OF(tstamped_message), L"AUDIT_SUCCESS ", _TRUNCATE);
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_NOTICE);
			break;
		case WINEVENT_VERBOSE_LEVEL:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_DEBUG);
			break;

		/* Everything else */
		default:
			level = SYSLOG_BUILD(SyslogFacility, SYSLOG_NOTICE);
			break;
	}

	/* Combine the message strings */
	wcsncat_s(tstamped_message, COUNT_OF(tstamped_message), formatted_string, _TRUNCATE);

	/* Send the event to the Syslog Server */
	/* Making sure it is severe enough to be logged */
	if (SyslogLogLevel == 0 || (SyslogLogLevel >= (DWORD)winlevel && winlevel > 0))
		if (SyslogSendW(tstamped_message, level))
			status = ERR_FAIL;

	/* Cleanup memory and open handles */
	if(pwsMessage)
		free(pwsMessage);
	if(eventInfo)
		free(eventInfo);

	if (hProviderMetadata)
		EvtClose(hProviderMetadata);
	if (hEvent)
		EvtClose(hEvent);

	return status;
}
/**
* @brief Enumerate all the events in the result set.
* @param eventHandle A handle to an event.
*
* @return returns Print event status.
*/
DWORD EventLogReader::PrintEvent(EVT_HANDLE eventHandle)
{
    EVT_HANDLE context = nullptr;
    PEVT_VARIANT renderedValues = nullptr;
    DWORD status = ERROR_SUCCESS;
    do
    {
        // Identify the components of the event that you want to render. In this case,
        // render the system section of the event.
        context = EvtCreateRenderContext(0, nullptr, EvtRenderContextSystem);
        if (context == nullptr)
        {
            status = GetLastError();
            break;
        }
        // When you render the user data or system section of the event, you must specify
        // the EvtRenderEventValues flag. The function returns an array of variant values
        // for each element in the user data or system section of the event. For user data
        // or event data, the values are returned in the same order as the elements are
        // defined in the event. For system data, the values are returned in the order defined
        // in the EVT_SYSTEM_PROPERTY_ID enumeration.
        DWORD bufferSize = 0;
        DWORD bufferUsed = 0;
        DWORD propertyCount = 0;
        if (!EvtRender(context, eventHandle, EvtRenderEventValues, bufferSize, renderedValues, &bufferUsed, &propertyCount))
        {
            status = GetLastError();
            if (status == ERROR_INSUFFICIENT_BUFFER)
            {
                bufferSize = bufferUsed;
                renderedValues = (PEVT_VARIANT)malloc(bufferSize);
                if (renderedValues != nullptr)
                {
                    EvtRender(context, eventHandle, EvtRenderEventValues, bufferSize, renderedValues, &bufferUsed, &propertyCount);
                    status = GetLastError();
                }
                else
                {
                    status = ERROR_OUTOFMEMORY;
                    break;
                }
            }
            if (status != ERROR_SUCCESS)
                break;
        }
        std::map<std::string, std::string> eventData;

        std::wstring tempBuf = (renderedValues[EvtSystemProviderName].StringVal) ? renderedValues[EvtSystemProviderName].StringVal : L"";
        eventData["providername"] = base::wstring_to_string(tempBuf);
        if (renderedValues[EvtSystemProviderGuid].GuidVal != nullptr)
        {
            WCHAR guid[50] = {0};
            StringFromGUID2(*(renderedValues[EvtSystemProviderGuid].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));
            eventData["providerguid"] = base::wstring_to_string(guid);
        }

        DWORD eventId = renderedValues[EvtSystemEventID].UInt16Val;
        if (renderedValues[EvtSystemQualifiers].Type == EvtVarTypeNull)
            eventId = MAKELONG(renderedValues[EvtSystemEventID].UInt16Val, renderedValues[EvtSystemQualifiers].UInt16Val);
        char buf[1024] = { 0 };
        snprintf(buf, sizeof(buf), "%lu", eventId);
        eventData["eventid"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemVersion].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemVersion].ByteVal);
        eventData["version"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemLevel].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemLevel].ByteVal);
        eventData["level"] = buf;

        snprintf(buf, sizeof(buf), "%hu", (renderedValues[EvtSystemTask].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemTask].ByteVal);
        eventData["task"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemOpcode].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemOpcode].UInt16Val);
        eventData["opcode"] = buf;

        snprintf(buf, sizeof(buf), "%0x%I64x", (renderedValues[EvtSystemKeywords].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemOpcode].UInt64Val);
        eventData["keywords"] = buf;

        ULONGLONG ullTimeStamp = renderedValues[EvtSystemTimeCreated].FileTimeVal;
        FILETIME ft;
        ft.dwHighDateTime = (DWORD)((ullTimeStamp >> 32) & 0xFFFFFFFF);
        ft.dwLowDateTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
        SYSTEMTIME st;
        FileTimeToSystemTime(&ft, &st);
        ULONGLONG ullNanoseconds = (ullTimeStamp % 10000000) * 100; // Display nanoseconds instead of milliseconds for higher resolution
        snprintf(buf, sizeof(buf), "%02d/%02d/%02d %02d:%02d:%02d.%I64u", st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, ullNanoseconds);
        eventData["timecreated"] = buf;

        snprintf(buf, sizeof(buf), "%I64u", renderedValues[EvtSystemEventRecordId].UInt64Val);
        eventData["eventrecordid"] = buf;

        if (renderedValues[EvtSystemActivityID].Type != EvtVarTypeNull)
        {
            WCHAR guid[50] = { 0 };
            StringFromGUID2(*(renderedValues[EvtSystemActivityID].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));;
            eventData["activityid"] = base::wstring_to_string(guid);
        }

        if (renderedValues[EvtSystemRelatedActivityID].Type != EvtVarTypeNull)
        {
            WCHAR guid[50] = { 0 };
            StringFromGUID2(*(renderedValues[EvtSystemRelatedActivityID].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));;
            eventData["relatedactivityid"] = base::wstring_to_string(guid);
        }

        snprintf(buf, sizeof(buf), "%lu", renderedValues[EvtSystemProcessID].UInt32Val);
        eventData["processid"] = buf;

        snprintf(buf, sizeof(buf), "%lu", renderedValues[EvtSystemThreadID].UInt32Val);
        eventData["threadid"] = buf;

        tempBuf = (renderedValues[EvtSystemChannel].Type == EvtVarTypeNull) ? renderedValues[EvtSystemChannel].StringVal : L"";
        eventData["channel"] = base::wstring_to_string(tempBuf);

        eventData["computer"] = base::wstring_to_string(renderedValues[EvtSystemComputer].StringVal);

        if (renderedValues[EvtSystemUserID].Type != EvtVarTypeNull)
        {
            LPWSTR pwsSid = nullptr;
            if (ConvertSidToStringSid(renderedValues[EvtSystemUserID].SidVal, &pwsSid))
            {
                eventData["secuserid"] = base::wstring_to_string(pwsSid);
                LocalFree(pwsSid);
            }
        }
        // Get the handle to the provider's metadata that contains the message strings.
        EVT_HANDLE providerMetadata = EvtOpenPublisherMetadata(nullptr, renderedValues[EvtSystemProviderName].StringVal, nullptr, 0, 0);
        if (providerMetadata == nullptr)
            break;
        eventData["message"] = GetMessageString(providerMetadata, eventHandle);
        _printResultsCallback(eventData);
    } while (false);

    if (context)
        EvtClose(context);
    if (renderedValues)
        free(renderedValues);
    return status;
}
Beispiel #10
0
void DrawInputBar(InputWindow* inputWindow, int iCursorPos, Messages * msgup, Messages *msgdown ,unsigned int * iheight, unsigned int *iwidth)
{
    int i;
    char *strUp[MAX_MESSAGE_COUNT];
    char *strDown[MAX_MESSAGE_COUNT];
    int posUpX[MAX_MESSAGE_COUNT], posUpY[MAX_MESSAGE_COUNT];
    int posDownX[MAX_MESSAGE_COUNT], posDownY[MAX_MESSAGE_COUNT];
    int oldHeight = *iheight, oldWidth = *iwidth;
    int newHeight = 0, newWidth = 0;
    int cursor_pos=0;
    int inputWidth = 0, outputWidth = 0;
    int outputHeight = 0;
    FcitxInputState* input = &inputWindow->owner->owner->input;
    FcitxInstance* instance = inputWindow->owner->owner;
    int iChar = iCursorPos;
    int strWidth = 0, strHeight = 0;
    int fontSize = FONTHEIGHT;

    if (!IsMessageChanged(msgup) && !IsMessageChanged(msgdown))
        return;

    inputWidth = 0;
    strHeight = FONTHEIGHT;

    for (i = 0; i < GetMessageCount(msgup) ; i++)
    {
        char *trans = ProcessOutputFilter(instance, GetMessageString(msgup, i));
        if (trans)
            strUp[i] = trans;
        else
            strUp[i] = GetMessageString(msgup, i);
        posUpX[i] = MarginLeft + inputWidth;

        strWidth = StringWidth(inputWindow->dpy, inputWindow->owner->xftfont, strUp[i]);

        posUpY[i] = MarginTop + InputPos - strHeight;
        inputWidth += strWidth;
        if (input->bShowCursor)
        {
            int length = strlen(GetMessageString(msgup, i));
            if (iChar >= 0)
            {
                if (iChar < length)
                {
                    char strTemp[MESSAGE_MAX_LENGTH];
                    char *strGBKT = NULL;
                    strncpy(strTemp, strUp[i], iChar);
                    strTemp[iChar] = '\0';
                    strGBKT = strTemp;
                    strWidth = StringWidth(inputWindow->dpy, inputWindow->owner->xftfont, strGBKT);
                    cursor_pos= posUpX[i]
                                + strWidth + 2;
                }
                iChar -= length;
            }
        }

    }

    if (iChar >= 0)
        cursor_pos = inputWidth + MarginLeft;

    outputWidth = 0;
    outputHeight = 0;
    int currentX = 0;
    for (i = 0; i < GetMessageCount(msgdown) ; i++)
    {
        char *trans = ProcessOutputFilter(instance, GetMessageString(msgdown, i));
        if (trans)
            strDown[i] = trans;
        else
            strDown[i] = GetMessageString(msgdown, i);

        if (inputWindow->owner->bVerticalList) /* vertical */
        {
            if (GetMessageType(msgdown, i) == MSG_INDEX)
            {
                if (currentX > outputWidth)
                    outputWidth = currentX;
                if (i != 0)
                {
                    outputHeight += fontSize + 2;
                    currentX = 0;
                }
            }
            posDownX[i] = MarginLeft + currentX;
            strWidth = StringWidth(inputWindow->dpy, inputWindow->owner->xftfont, strDown[i]);
            currentX += strWidth;
            posDownY[i] =  MarginTop + OutputPos + outputHeight - strHeight;
        }
        else /* horizontal */
        {
            posDownX[i] = MarginLeft + outputWidth;
            strWidth = StringWidth(inputWindow->dpy, inputWindow->owner->xftfont, strDown[i]);
            posDownY[i] = MarginTop + OutputPos - strHeight;
            outputWidth += strWidth;
        }
    }
    if (inputWindow->owner->bVerticalList && currentX > outputWidth)
        outputWidth = currentX;

    newHeight = MarginTop + OutputPos + outputHeight + MarginBottom;

    newWidth = (inputWidth<outputWidth)?outputWidth:inputWidth;
    newWidth+=MarginLeft+MarginRight;

    /* round to ROUND_SIZE in order to decrease resize */
    newWidth =  (newWidth / ROUND_SIZE) * ROUND_SIZE + ROUND_SIZE;

    //输入条长度应该比背景图长度要长,比最大长度要短
    newWidth=(newWidth>=INPUT_BAR_MAX_WIDTH)?INPUT_BAR_MAX_WIDTH:newWidth;
    if (inputWindow->owner->bVerticalList) /* vertical */
    {
        newWidth = (newWidth < INPUT_BAR_VMIN_WIDTH)?INPUT_BAR_VMIN_WIDTH:newWidth;
    }
    else
    {
        newWidth = (newWidth < INPUT_BAR_HMIN_WIDTH)?INPUT_BAR_HMIN_WIDTH:newWidth;
    }

    *iwidth = newWidth;
    *iheight = newHeight;

    if (oldHeight != newHeight || oldWidth != newWidth)
    {
        DrawResizableBackground(inputWindow->owner, inputWindow->pixmap2, newHeight, newWidth,
                                inputWindow->owner->backcolor,
                                inputWindow->owner->bordercolor,
                                inputWindow->pixmap2_gc
                               );
    }
    XGCValues gcvalues;
    GC gc = XCreateGC(inputWindow->dpy, inputWindow->pixmap, 0, &gcvalues);
    XCopyArea(
        inputWindow->dpy,
        inputWindow->pixmap2,
        inputWindow->pixmap,
        gc,
        0, 0,
        inputWindow->iInputWindowWidth,
        inputWindow->iInputWindowHeight,
        0, 0
    );
    XFreeGC(inputWindow->dpy, gc);
    if (input->bShowCursor )
    {
        //画向前向后箭头
    }

    for (i = 0; i < GetMessageCount(msgup) ; i++)
    {
        OutputString(inputWindow->dpy, inputWindow->xftDraw, inputWindow->pixmap, inputWindow->owner->xftfont, strUp[i], posUpX[i], posUpY[i], inputWindow->owner->fontColor[GetMessageType(msgup, i)]);
        if (strUp[i] != GetMessageString(msgup, i))
            free(strUp[i]);
    }

    for (i = 0; i < GetMessageCount(msgdown) ; i++)
    {
        OutputString(inputWindow->dpy, inputWindow->xftDraw, inputWindow->pixmap, inputWindow->owner->xftfont, strDown[i], posDownX[i], posDownY[i], inputWindow->owner->fontColor[GetMessageType(msgdown, i)]);
        if (strDown[i] != GetMessageString(msgdown, i))
            free(strDown[i]);
    }

    //画光标
    if (input->bShowCursor )
    {
        GC gc = LightUICreateGC(inputWindow->dpy, inputWindow->pixmap, inputWindow->owner->cursorColor);
        XDrawLine(inputWindow->dpy, inputWindow->pixmap, gc, cursor_pos, MarginTop + InputPos,
                  cursor_pos, MarginTop + InputPos - fontSize - 4);
        XFreeGC(inputWindow->dpy, gc);
    }

    SetMessageChanged(msgup, false);
    SetMessageChanged(msgdown, false);
}
Beispiel #11
0
int main( int argc, char *argv[] )     {
    struct event *eventptr;
    struct msg   msg2give;
    struct pkt   pkt2give;
   
    int          currentEntity;
    int          i,j;
  
//  Do our initialization and any requested by student's Transport Layer 
    CallingArgc = argc;
    CallingArgv = argv;
    init( );
    A_init();
    B_init();
   
    /* ***********************************************************************
      We loop here forever.  During these actions we get an event off the
      event header.  We analyze the action to be performed and go do it.
    *************************************************************************/
    while (TRUE) {
        eventptr = evlist;        // get next event to simulate from Q head 
        if (eventptr==NULL)       //  IF nothing to simulate, we're done  
            break;

        evlist = evlist->next;    // remove this event from event list 
        if (evlist != NULL)       //   and sort out forward and back ptrs
            evlist->prev=NULL;

        // Update simulation time to event time  - by definition, the
        // simulation time is the time of the last event.
        CurrentSimTime = eventptr->evtime;        
        currentEntity = eventptr->eventity;
        // If we've delivered the required number of messages, then we've
        // fullfilled our task and are done.
        if ( NumMsgs4To5 >= MaxMsgsToSimulate )
            break;                            // all done with simulation 
        
        /* *******************************************************************
          Here we've gotten a request to hand data from layer 5 to layer 4.
            Generate the date we want to give to the student.                 
        *********************************************************************/
        if ( eventptr->evtype == FROM_LAYER5 ) {
            // Use the sequence number as starter for the message string
            j = GeneratingSeqNum[currentEntity]++;
            // printf( "%X  %d %d\n", &eventptr, currentEntity, j );
            GetMessageString( currentEntity, j, &(msg2give.data[0]) );
            /*  Always print trace so we know it matches the receive  */
            if ( TraceLevel >= 0 )  {    
                //printf("%c: ", &(EntityLetter[currentEntity]) );
                if ( currentEntity == AEntity )   
                    printf("A: " );
                else
                    printf("B: " );
                printf(" %11.4f,", eventptr->evtime);

                printf("  Layer 5 to 4  Message = ");
                for (i=0; i<MESSAGE_LENGTH; i++) 
                    printf("%c", msg2give.data[i]);
                printf("\n");
            }
            // The simulation will actually end when the requested number of
            // messages has been received back at layer 5.  But there could be
            // many packets in the system, and that total arrival could take
            // a long time.  We want to make sure we down't overwhelm the
            // student code with messages that won't ever be delivered anyway.
            //
            if ( NumMsgs5To4 <= MaxMsgsToSimulate + 3 ) { 
                GenerateNextArrival();           // set up future arrival 
                NumMsgs5To4++;                   // # msgs from layer 5 to 4 
            }
            if ( currentEntity == AEntity )  // Pass the data to layer 4 here 
                A_output(msg2give);  
            else
                B_output(msg2give);  
        }                              /* END of event is from layer 5 */

        /* *******************************************************************
          This is a request to hand data from layer 3 up to student layer 4 
        *********************************************************************/
        else if (eventptr->evtype ==  FROM_LAYER3 ) {
            pkt2give.seqnum   = eventptr->pktptr->seqnum;
            pkt2give.acknum   = eventptr->pktptr->acknum;
            pkt2give.checksum = eventptr->pktptr->checksum;
            for ( i = 0; i < MESSAGE_LENGTH; i++)  
                pkt2give.payload[i] = eventptr->pktptr->payload[i];

            if ( TraceLevel >= 2 )  {     /* Print out trace info if requested */
                if ( eventptr->eventity == AEntity )   
                    printf("A: " );
                else
                    printf("B: " );
                printf(" %11.4f,", eventptr->evtime);

                printf("  Layer 3 to 4  ");
                printf( "Seq/Ack/Check = %d/%d/%d:  ",
                        eventptr->pktptr->seqnum, eventptr->pktptr->acknum,
                        eventptr->pktptr->checksum );
                for (i=0; i<MESSAGE_LENGTH; i++) 
                    printf("%c", eventptr->pktptr->payload[i] );
                printf("\n");
            }
            if (eventptr->eventity == AEntity)   /* deliver packet by calling */
                   A_input(pkt2give);            /* appropriate entity */
            else
                   B_input(pkt2give);
            free(eventptr->pktptr);          /* free the memory for packet */
        }                             /* END of event is from layer 3 */

        /* *******************************************************************
              This is a request for a timer interrupt 
        *********************************************************************/
        else if (eventptr->evtype ==  TIMER_INTERRUPT) {
            if ( TraceLevel >= 2 )  {     /* Print out trace info if requested */
                if ( eventptr->eventity == AEntity )   
                    printf("A: " );
                else
                    printf("B: " );
                printf(" %f,", eventptr->evtime);
                printf("  Timer Interrupt\n");
            }
            if (eventptr->eventity == AEntity) 
                A_timerinterrupt();
            else
                B_timerinterrupt();
        }                             /* END of event is interrupt request */
        else  {
            printf("INTERNAL PANIC: unknown event type \n");
        }
        free(eventptr);
    }                       // End of while

terminate:
    printf("\n\nSimulator terminated at time %f\n after receiving %d msgs at layer5\n",
                  CurrentSimTime, NumMsgs4To5 );
    printf( "Simulator Analysis:\n");
    printf( "  Number of messages sent from 5 to 4: %d\n", NumMsgs5To4 );
    printf( "  Number of messages received at Layer 5, side A: %d\n",
                  ExpectedSeqNum[0]  );
    printf( "  Number of messages received at Layer 5, side B: %d\n",
                  ExpectedSeqNum[1]  );
    printf( "  Number of messages incorrectly received at layer 5: %d\n", 
                  NumMsgs5To4WithErr );
    printf( "  Number of packets entering the network: %d\n", NumMsgs4To3 );
    printf( "  Average number of packets already in network: %6.3f\n",
               (double)NumSimutaneousMsgs /  (double)NumMsgs4To3 );
    printf( "  Number of packets that the network lost: %d\n", NumMsgsLost );
    printf( "  Number of packets that the network corrupted: %d\n", 
                   NumMsgsCorrupt );
    printf( "  Number of packets that the network put out of order: %d\n", 
                   NumMsgsOutOfOrder );
    return 0;
}