1
0
mirror of https://github.com/dkmstr/openuds.git synced 2024-12-22 13:34:04 +03:00

Removed old actors

This commit is contained in:
Adolfo Gómez García 2014-12-09 17:17:36 +01:00
parent 22bf17f080
commit 8e7a6af3ad
107 changed files with 0 additions and 66146 deletions

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>linuxActor</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?><pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property>
<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
<path>/linuxActor/src</path>
</pydev_pathproperty>
</pydev_project>

View File

@ -1,26 +0,0 @@
LIBDIR = $(DESTDIR)/usr/share/pyshared/udsactor
BINDIR = $(DESTDIR)/usr/bin
CFGDIR = $(DESTDIR)/etc/udsactor
clean:
rm -f *.py[co] */*.py[co]
install:
mkdir -p $(LIBDIR)
mkdir -p $(BINDIR)
mkdir -p $(CFGDIR)
mkdir -p $(LIBDIR)/uds/actor/renamer
cp actor.py $(LIBDIR)/
cp uds/*.py $(LIBDIR)/uds
cp uds/actor/*.py $(LIBDIR)/uds/actor
cp uds/actor/renamer/*.py $(LIBDIR)/uds/actor/renamer
cp runActor.sh $(BINDIR)/udsactor
cp udsactor.cfg $(CFGDIR)
chmod 0755 $(BINDIR)/udsactor
uninstall:
rm -rf $(LIBDIR)
rm -f $(BINDIR)/udsactor
rm -rf $(CFGDIR)

View File

@ -1,105 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Nov 16, 2011
@author: dkmaster
'''
import sys
import time
import logging
import re
from uds.actor.daemon import Daemon
from uds.actor.rpc import Rpc
from uds.actor import net
from uds.actor.renamer import rename
logger = logging.getLogger('uds')
class MyDaemon(Daemon):
def run(self):
splitRe = re.compile('\r|\n')
while True:
# Wait for networks to become ready
info = net.getExternalIpAndMacs()
if len(info) > 0:
break
time.sleep(4)
# Now, get info of what to do
Rpc.initialize()
# waits for a valid command (maybe broker down or not reachable, so we loop here till we know what to do (that is, broker is reachable))
todo = None
while todo is None:
Rpc.resetId()
todo = Rpc.getInfo()
if todo is None:
time.sleep(4)
# We can get 'rename:newname', ''. Anything else is an error
data = splitRe.split(todo)
if data[0] == 'rename':
logger.info('Renaming to {0}'.format(data[1]))
rename(data[1])
Rpc.setReady()
elif todo == '':
logger.info('Unmanaged machine')
# Unmanaged machine, exit
return
else:
# Error, log and exit
logger.error('Unknown command received: {0}'.format(todo))
return
# Keep notifiyin ip changes
info = net.getExternalIpAndMacs()
# We have "info" with know interfaces
while True:
try:
newInfo = net.getExternalIpAndMacs()
for k in info.keys():
if info[k]['ip'] != newInfo[k]['ip']:
if Rpc.notifyIpChange() is not None:
info = newInfo
else:
logger.info('Could not notify IP address. Will retry later.')
break
time.sleep(5)
except:
logger.exception('Exception caught at main loop!')
return
if __name__ == '__main__':
if len(sys.argv) == 3:
if 'login' == sys.argv[1]:
logger.debug('Notify login')
Rpc.initialize()
Rpc.login(sys.argv[2])
sys.exit(0)
elif 'logout' == sys.argv[1]:
logger.debug('Notify logout')
Rpc.initialize()
Rpc.logout(sys.argv[2])
sys.exit(0)
logger.debug('Executing actor')
daemon = MyDaemon('/var/run/udsactor.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart|login 'username'|logout 'username'" % sys.argv[0]
sys.exit(2)

View File

@ -1,9 +0,0 @@
udsactor (1.1) stable; urgency=medium
* Fixing IP notification issues
-- Adolfo Gómez García <agomez@virtualcable.es> Fri, 23 May 2014 13:00:32 +0200
udsactor (1.0) stable; urgency=low
* Initial version
-- Adolfo Gómez García <agomez@virtualcable.es> Fri, 18 Nov 2011 05:35:11 +0100

View File

@ -1 +0,0 @@
7

View File

@ -1,46 +0,0 @@
#!/bin/bash -e
. /usr/share/debconf/confmodule
Q=0
Q_DONE=3
nextState() {
if [[ $1 -eq 30 ]]; then
Q=$((Q-1))
else
Q=$((Q+1))
fi
}
if [[ -f /etc/udsactor/udsactor.cfg ]]; then
TMPFILE=$(mktemp /tmp/udsactor.cfg.XXXXX)
trap "rm -f $TMPFILE" 0
cat /etc/udsactor/udsactor.cfg | sed -e "s/\\[.*\\]//; s/ *= */=/; s/False/false/; s/True/true/" > $TMPFILE
. $TMPFILE
db_set udsactor/server $server
db_set udsactor/secure $ssl
db_set udsactor/timeout $timeout
fi
db_capb backup
while [[ $Q -lt $Q_DONE ]]; do
case $Q in
0)
db_input high udsactor/server || true
db_go || true
nextState 0
;;
1)
db_input high udsactor/secure || true
db_go || RET=$?
nextState $RET
;;
2)
db_input high udsactor/timeout || true
db_go || RET=$?
nextState 0
;;
esac
done

View File

@ -1 +0,0 @@
/etc/udsactor/udsactor.cfg

View File

@ -1,14 +0,0 @@
Source: udsactor
Section: contrib/net
Priority: extra
Maintainer: Adolfo Gómez García <agomez@virtualcable.es>
Build-Depends: debhelper (>= 7), po-debconf
Standards-Version: 3.9.2
Homepage: http://www.virtualcable.es
Package: udsactor
Architecture: all
Depends: python (>= 2.6), ${misc:Depends}
Description: UDS Actor for Universal Destop Services
This package provides the actor needed for integration of
debian with uds services platform.

View File

@ -1,26 +0,0 @@
Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=135
Name: udsactor
Maintainer: Adolfo Gómez García
Source: http://www.udsenterprise.com/
Copyright: 2014 Virtual Cable S.L.U.
License: BSD-3-clause
License: GPL-2+
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
.
On Debian systems, the full text of the GNU General Public
License version 2 can be found in the file
`/usr/share/common-licenses/GPL-2'.

View File

@ -1,2 +0,0 @@
/usr/bin/
/usr/share/pyshared/udsactor

View File

@ -1 +0,0 @@
readme.txt

View File

@ -1 +0,0 @@
udsactor_1.1_all.deb contrib/net extra

View File

@ -1,24 +0,0 @@
#!/bin/sh -e
### BEGIN INIT INFO
# Provides: uds-actor
# Required-Start: $local_fs $remote_fs $network $syslog $named
# Required-Stop: $local_fs $remote_fs $network $syslog $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: UDS Actor
### END INIT INFO
#
. /lib/lsb/init-functions
case "$1" in
start|stop|restart)
/usr/bin/udsactor $1
;;
force-reload)
./actor restart
;;
*) echo "Usage: $0 {start|stop|restart|force-reload}" >&2; exit 1 ;;
esac

View File

@ -1 +0,0 @@
[type: gettext/rfc822deb] templates

View File

@ -1,58 +0,0 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: agomez@virtualcable.es\n"
"POT-Creation-Date: 2011-11-21 11:40+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#. Type: string
#. Description
#: ../templates:1001
msgid "UDS Server address:"
msgstr ""
#. Type: string
#. Description
#: ../templates:1001
msgid ""
"The actor needs the address of the server in order to communicate with it. "
"Provide here full address (or i) of the UDS server"
msgstr ""
#. Type: boolean
#. Description
#: ../templates:2001
msgid "Use secure (https) connection to communicate with UDS server?"
msgstr ""
#. Type: boolean
#. Description
#: ../templates:2001
msgid ""
"If selected, the communication will be done using https. If not selected, "
"the communication will be done using http"
msgstr ""
#. Type: string
#. Description
#: ../templates:3001
msgid "Timeout in communications with UDS server:"
msgstr ""
#. Type: string
#. Description
#: ../templates:3001
msgid "The timeout is expressed in seconds"
msgstr ""

View File

@ -1,38 +0,0 @@
#!/bin/sh
. /usr/share/debconf/confmodule
set -e
case "$1" in
configure)
# Ensure actor is not running
db_get udsactor/server
server=$RET
db_get udsactor/secure
ssl=$RET
if [ "$ssl" = "true" ]; then ssl=True; else ssl=False; fi
db_get udsactor/timeout
timeout=$RET
TMPFILE=$(mktemp /tmp/udsactor.cfg.XXXXX)
trap "rm -f $TMPFILE" 0
cat /etc/udsactor/udsactor.cfg | sed -e "s/server=.*/server=$server/; s/ssl=.*/ssl=$ssl/; s/timeout=.*/timeout=$timeout/" > $TMPFILE
cp $TMPFILE /etc/udsactor/udsactor.cfg
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
#DEBHELPER#
# Don't know why, but descriptors get "weird" when launched daemon, so we tell here to debconf to stop.
# Solved not starting the service right now, defered to next reboot
exit 0

View File

@ -1,44 +0,0 @@
#!/usr/bin/make -f
# -*- makefile -*-
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build: build-arch build-indep
build-arch: build-stamp
build-indep: build-stamp
build-stamp: configure-stamp
dh_testdir
$(MAKE)
touch $@
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
dh_clean
install: build
dh_testdir
dh_testroot
dh_prep
dh_installdirs
$(MAKE) DESTDIR=$(CURDIR)/debian/udsactor install
binary-arch: build install
# emptyness
binary-indep: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_installdebconf
dh_installinit --no-start
dh_python2=python
dh_compress
dh_link
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep
.PHONY: build clean binary-indep binary install configure

View File

@ -1,19 +0,0 @@
Template: udsactor/server
Type: string
Default:
_Description: UDS Server address:
The actor needs the address of the server in order to communicate with it.
Provide here full address (or i) of the UDS server
Template: udsactor/secure
Type: boolean
Default: true
_Description: Use secure (https) connection to communicate with UDS server?
If selected, the communication will be done using https.
If not selected, the communication will be done using http
Template: udsactor/timeout
Type: string
Default: 5
_Description: Timeout in communications with UDS server:
The timeout is expressed in seconds

View File

@ -1 +0,0 @@
This package provides the actor needed for using with UDS infrastructure.

View File

@ -1,4 +0,0 @@
#!/bin/sh
cd /usr/share/pyshared/udsactor
python actor.py $@

View File

@ -1,26 +0,0 @@
# -*- coding: utf-8 -*-
'''
Created on Nov 16, 2011
@author: dkmaster
'''
import logging, logging.handlers
from config import config
# Initializes logging facility (don't using dictConfig)
log = logging.getLogger('uds')
log.setLevel(config['debug'])
formatter = logging.Formatter('%(levelname)s %(asctime)s %(module)s %(message)s')
fileHandler = logging.handlers.RotatingFileHandler(filename = config['log'], mode = 'a', maxBytes = config['maxsize'], backupCount = config['backups'], encoding = 'utf-8')
fileHandler.setLevel(logging.DEBUG)
fileHandler.setFormatter(formatter)
#streamHandler = logging.StreamHandler()
#streamHandler.setLevel(logging.DEBUG)
#streamHandler.setFormatter(formatter)
log.addHandler(fileHandler)
#log.addHandler(streamHandler)

View File

@ -1,52 +0,0 @@
'''
Created on Nov 17, 2011
@author: dkmaster
'''
import os
# Config file format:
# [broker]
# server = host:port (required)
# ssl = [True|False] (defaults to False)
# timeout = Timeout in seconds for xmlrpc (defaults to 10)
# [logging]
# log = /path/to/log (required, defaults to /tmp/udsactor.log)
# debug = [ERROR|INFO|DEBUG|WARN| (defaults to ERROR)
# maxsize = Max size of log file, in megas (defaults to 20)
# backups = Number of backups to keep of log file (defaults to 3)
import ConfigParser
import logging
import sys
CONFIGFILE = '/etc/udsactor/udsactor.cfg'
cfg = ConfigParser.SafeConfigParser(defaults={ 'server' : '', 'ssl' : False, 'timeout' : '10',
'log' : '/tmp/udsactor.log', 'debug' : 'ERROR', 'maxsize' : '20', 'backups' : '3' })
cfg.read(CONFIGFILE)
levels = {
'WARN' : logging.WARN,
'INFO' : logging.INFO,
'DEBUG': logging.DEBUG,
'ERROR': logging.ERROR
}
try:
config = {
'server' : cfg.get('broker', 'server'),
'ssl' : cfg.getboolean('broker', 'ssl'),
'timeout' : cfg.getint('broker', 'timeout'),
'log' : cfg.get('logging', 'log'),
'debug' : levels.get(cfg.get('logging', 'debug'), logging.ERROR),
'maxsize' : cfg.getint('logging', 'maxsize') * 1024 * 1024,
'backups' : cfg.getint('logging', 'backups')
}
# Config file is used only in "root mode", in user mode we overwrite it
if os.getuid() != 0:
config['log'] = os.getenv('HOME', '/tmp') + "/udsactor.log"
except Exception, e:
sys.stderr.write("Error reading configuration file: " + str(e))
sys.exit(2)

View File

@ -1,139 +0,0 @@
# -*- coding: utf-8 -*-
'''
@author: : http://www.jejik.com/authors/sander_marechal/
@see: : http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
'''
import sys
import os
import time
import atexit
from signal import SIGTERM
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(self.stdin, 'r')
so = open(self.stdout, 'a+')
se = open(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile, 'w+') as f:
f.write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = open(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while True:
os.kill(pid, SIGTERM)
time.sleep(1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""

View File

@ -1,71 +0,0 @@
'''
@author: Ben Mackey (getHwAddr) and paul cannon (getIpAddr)
@see: http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/
'''
import fcntl, socket, struct, array, platform
import logging
logger = logging.getLogger(__name__)
def getMacAddr(ifname):
if isinstance(ifname, list):
return dict([ (name, getMacAddr(name)) for name in ifname ])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
except Exception:
return None
def getIpAddr(ifname):
if isinstance(ifname, list):
return dict([ (name, getIpAddr(name)) for name in ifname ])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
except Exception:
return None
def getInterfaces():
max_possible = 128 # arbitrary. raise if needed.
space = max_possible * 16
if platform.architecture()[0] == '32bit':
offset, length = 32, 32
elif platform.architecture()[0] == '64bit':
offset, length = 16, 40
else:
raise OSError('Unknown arquitecture {0}'.format(platform.architecture()[0]))
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * space)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno(),
0x8912, # SIOCGIFCONF
struct.pack('iL', space, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [namestr[i:i + offset].split('\0', 1)[0] for i in range(0, outbytes, length)]
def getIpAndMac(ifname):
ip, mac = getIpAddr(ifname), getMacAddr(ifname)
if isinstance(ifname, list):
return dict([ (key, { 'ip': ip[key], 'mac': mac[key] }) for key in ip.keys() ])
return (ip, mac)
def getExternalIpAndMacs():
res = getIpAndMac(getInterfaces())
# logger.debug('Res: {0}'.format(res))
for key in res.keys():
if res[key]['mac'] == '00:00:00:00:00:00':
del res[key]
return res

View File

@ -1,28 +0,0 @@
# -*- coding: utf-8 -*-
'''
Created on Nov 17, 2011
@author: dkmaster
'''
import platform
import logging
import os
import sys
import pkgutil
logger = logging.getLogger(__name__)
renamers = {}
def rename(newName):
distribution = platform.linux_distribution()[0].lower()
if distribution in renamers:
return renamers[distribution](newName)
logger.error('Renamer for platform "{0}" not found'.format(distribution))
return False
pkgpath = os.path.dirname(sys.modules[__name__].__file__)
for _, name, _ in pkgutil.iter_modules([pkgpath]):
__import__(name, globals(), locals())

View File

@ -1,46 +0,0 @@
# -*- coding: utf-8 -*-
'''
Created on Nov 17, 2011
@author: dkmaster
'''
from . import renamers
import logging, os
logger = logging.getLogger(__name__)
def rename(newName):
# If new name has "'\t'
if '\t' in newName:
newName, account, password = newName.split('\t')
else:
account = password = None
logger.debug('Debian renamer')
if account is not None:
os.system('echo "{1}\n{1}" | /usr/bin/passwd {0} 2> /dev/null'.format(account, password))
f = open('/etc/hostname', 'w')
f.write(newName)
f.close()
os.system('/bin/hostname %s' % newName)
# add name to "hosts"
f = open('/etc/hosts', 'r')
lines = f.readlines()
f.close()
f = open('/etc/hosts', 'w')
f.write("127.0.1.1\t%s\n" % newName)
for l in lines:
if l[:9] == '127.0.1.1':
continue
f.write(l)
f.close()
return True
# All names in lower case
renamers['debian'] = rename
renamers['ubuntu'] = rename

View File

@ -1,90 +0,0 @@
# -*- coding: utf-8 -*-
'''
Created on Nov 17, 2011
@author: dkmaster
'''
import logging, xmlrpclib, socket
import net
from config import config
logger = logging.getLogger(__name__)
LOGIN_MSG = 'login'
LOGOUT_MSG = 'logout'
READY_MSG = 'ready'
INFO_MSG = 'information'
IP_MSG = 'ip'
class Rpc(object):
_manager = None
def __init__(self, broker, ssl, timeout=10):
url = (ssl and 'https' or 'http') + '://' + broker + '/xmlrpc'
logger.debug('Remote address: {0}'.format(url))
self._server = xmlrpclib.ServerProxy(uri=url, verbose=False)
self._id = None
socket.setdefaulttimeout(timeout)
@staticmethod
def initialize():
Rpc._manager = Rpc(config['server'], config['ssl'], config['timeout'])
def test(self):
try:
self._server.test()
logger.debug('Test successful')
return True
except Exception:
logger.error('Test unsuccessful')
return False
def message(self, msg, data):
try:
if self._id is None:
self._id = ','.join([ v['mac'] for v in net.getExternalIpAndMacs().values() ])
logger.debug('Sending message to broker: {0} -> {1}, {2}'.format(self._id, msg, data))
return self._server.message(self._id, msg, data)
except Exception as e:
logger.exception('Error notifying message')
return None
return ''
@staticmethod
def login(username):
if Rpc._manager is None: # Not managed
return
return Rpc._manager.message(LOGIN_MSG, username)
@staticmethod
def logout(username):
if Rpc._manager is None: # Not managed
return
return Rpc._manager.message(LOGOUT_MSG, username)
@staticmethod
def getInfo():
if Rpc._manager is None: # Not managed
return
return Rpc._manager.message(INFO_MSG, '')
@staticmethod
def setReady():
if Rpc._manager is None: # Not managed
return
interfaces = ','.join([v['mac'] + '=' + v['ip'] for v in net.getExternalIpAndMacs().values()])
return Rpc._manager.message(READY_MSG, interfaces)
@staticmethod
def notifyIpChange():
if Rpc._manager is None: # Not managed
return None
interfaces = ','.join([ v['mac'] + '=' + v['ip'] for v in net.getExternalIpAndMacs().values() ])
return Rpc._manager.message(IP_MSG, interfaces)
@staticmethod
def resetId():
logger.debug('Reseting rpc id')
Rpc._manager._id = None

View File

@ -1,13 +0,0 @@
[broker]
server=192.168.0.1
ssl=False
timeout=5
[logging]
debug=INFO
log=/var/log/udsactor.log
# Size in megas
maxsize=20
backups=3

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>linuxActorNX</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>

View File

@ -1,13 +0,0 @@
BINDIR = $(DESTDIR)/usr/bin
clean:
echo "Clean"
install:
mkdir -p $(BINDIR)
cp udsnxstart.sh $(BINDIR)/udsnxstart
cp udsnxstop.sh $(BINDIR)/udsnxstop
chmod 0755 $(BINDIR)/udsnxstart
chmod 0755 $(BINDIR)/udsnxstop
uninstall:
echo "Uninstall"

View File

@ -1,9 +0,0 @@
udsactor-nx (1.1) stable; urgency=medium
* Updated dependencies
-- Adolfo Gómez García <agomez@virtualcable.es> Fri, 23 Jun 2014 13:00:32 +0200
udsactor-nx (1.0) stable; urgency=low
* Initial version
-- Adolfo Gómez García <agomez@virtualcable.es> Fri, 21 Nov 2011 23:35:11 +0100

View File

@ -1 +0,0 @@
7

View File

@ -1,14 +0,0 @@
Source: udsactor-nx
Section: contrib/net
Priority: extra
Maintainer: Adolfo Gómez García <agomez@virtualcable.es>
Build-Depends: debhelper (>= 7)
Standards-Version: 3.9.2
Homepage: http://www.virtualcable.es
Package: udsactor-nx
Architecture: all
Depends: nxnode (>= 3.5.0), udsactor (>= 1.0), ${misc:Depends}
Description: UDS Actor component for nx
This package provides connection between uds actor and nx

View File

@ -1,26 +0,0 @@
Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=135
Name: udsactor-nx
Maintainer: Adolfo Gómez García
Source: http://www.udsenterprise.com/
Copyright: 2014 Virtual Cable S.L.
License: BSD-3-clause
License: GPL-2+
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
.
On Debian systems, the full text of the GNU General Public
License version 2 can be found in the file
`/usr/share/common-licenses/GPL-2'.

View File

@ -1 +0,0 @@
readme.txt

View File

@ -1 +0,0 @@
udsactor-nx_1.1_all.deb contrib/net extra

View File

@ -1,37 +0,0 @@
#!/bin/sh
NXNODECFG=/usr/NX/etc/node.cfg
. /usr/share/debconf/confmodule
set -e
case "$1" in
configure)
TMPFILE=$(mktemp /tmp/node.cfg.XXXXX)
trap "rm -f $TMPFILE" 0
cat $NXNODECFG | sed -e "s/.*udsnxst.*//; s/\(UserScriptAfterSessionStart *=.*\)/#\1/;s/\(UserScriptAfterSessionClose *=.*\)/#\1/" > $TMPFILE
echo >> $TMPFILE
echo "# Added by udsactor-nx (udsnxstart and udsnxstop)" >> $TMPFILE
echo UserScriptAfterSessionStart = \"/usr/bin/udsnxstart\" >> $TMPFILE
echo UserScriptAfterSessionClose = \"/usr/bin/udsnxstop\" >> $TMPFILE
cp $TMPFILE $NXNODECFG
invoke-rc.d nxserver restart
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
#DEBHELPER#
# Don't know why, but descriptors get "weird" when launched daemon, so we tell here to debconf to stop.
# Solved not starting the service right now, defered to next reboot
exit 0

View File

@ -1,28 +0,0 @@
#!/bin/sh
NXNODECFG=/usr/NX/etc/node.cfg
. /usr/share/debconf/confmodule
set -e
case "$1" in
purge)
;;
remove)
TMPFILE=$(mktemp /tmp/node.cfg.XXXXX)
trap "rm -f $TMPFILE" 0
cat $NXNODECFG | sed -e "s/.*udsnxst.*//" > $TMPFILE
cp $TMPFILE $NXNODECFG
invoke-rc.d nxserver restart
;;
upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "postrm called with unknown argument \`$1'" >&2
exit 1
;;
esac
#DEBHELPER#

View File

@ -1,41 +0,0 @@
#!/usr/bin/make -f
# -*- makefile -*-
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build: build-arch build-indep
build-arch: build-stamp
build-indep: build-stamp
build-stamp: configure-stamp
dh_testdir
$(MAKE)
touch $@
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
dh_clean
install: build
dh_testdir
dh_testroot
dh_prep
dh_installdirs
$(MAKE) DESTDIR=$(CURDIR)/debian/udsactor-nx install
binary-arch: build install
# emptyness
binary-indep: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_compress
dh_link
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep
.PHONY: build clean binary-indep binary install configure

View File

@ -1 +0,0 @@
This package provides the interaction between nx and uds

View File

@ -1,3 +0,0 @@
#!/bin/sh
exec /usr/bin/udsactor login $2 &

View File

@ -1,3 +0,0 @@
#!/bin/sh
exec /usr/bin/udsactor logout $2 &

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.python.pydev.PyDevBuilder"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>linuxActorXRDP</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/org.python.pydev.PyDevBuilder.launch</value>
</dictionary>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?><pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
<path>/${PROJECT_DIR_NAME}/src</path>
</pydev_pathproperty>
</pydev_project>

View File

@ -1,13 +0,0 @@
BINDIR = $(DESTDIR)/usr/bin
clean:
echo "Clean"
install:
mkdir -p $(BINDIR)
cp uds-sesman.sh $(BINDIR)/uds-sesman
cp uds-wait-session.sh $(BINDIR)/uds-wait-session
chmod 0755 $(BINDIR)/uds-sesman
chmod 0755 $(BINDIR)/uds-wait-session
uninstall:
echo "Uninstall"

View File

@ -1,3 +0,0 @@
udsactor-xrdp (1.1) stable; urgency=low
* Initial version
-- Adolfo Gómez García <agomez@virtualcable.es> Thu, 10 jul 2014 15:31:18 +0100

View File

@ -1 +0,0 @@
7

View File

@ -1,14 +0,0 @@
Source: udsactor-xrdp
Section: contrib/net
Priority: extra
Maintainer: Adolfo Gómez García <agomez@virtualcable.es>
Build-Depends: debhelper (>= 7)
Standards-Version: 3.9.2
Homepage: http://www.udsenterprise.com
Package: udsactor-xrdp
Architecture: all
Depends: xrdp (>= 0.6.0), udsactor (>= 1.1), libpam-modules-bin (>=1.0), ${misc:Depends}
Description: UDS Actor component for xrdp
This package provides connection between uds actor and xrdp

View File

@ -1,26 +0,0 @@
Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=135
Name: udsactor-xrdp
Maintainer: Adolfo Gómez García
Source: http://www.udsenterprise.com/
Copyright: 2014 Virtual Cable S.L.
License: BSD-3-clause
License: GPL-2+
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
.
On Debian systems, the full text of the GNU General Public
License version 2 can be found in the file
`/usr/share/common-licenses/GPL-2'.

View File

@ -1 +0,0 @@
readme.txt

View File

@ -1 +0,0 @@
udsactor-xrdp_1.1_all.deb contrib/net extra

View File

@ -1,39 +0,0 @@
#!/bin/sh
SESMANFILE=/etc/pam.d/xrdp-sesman
. /usr/share/debconf/confmodule
set -e
case "$1" in
configure)
trap "cp $SESMANFILE $SESMANFILE.uds.old" 0
TMPFILE=$(mktemp /tmp/sesman.XXXXX)
trap "rm -f $TMPFILE" 0
grep -v uds $SESMANFILE > $TMPFILE # Removes all UDS lines from sesman if they exists
echo >> $TMPFILE
echo "# Added by udsactor-xrdp" >> $TMPFILE
echo "session optional pam_exec.so /usr/bin/uds-sesman" >> $TMPFILE
cp $TMPFILE $SESMANFILE
trap "rm -f $TMPFILE" 0
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
#DEBHELPER#
# Don't know why, but descriptors get "weird" when launched daemon, so we tell here to debconf to stop.
# Solved not starting the service right now, defered to next reboot
exit 0

View File

@ -1,28 +0,0 @@
#!/bin/sh
SESMANFILE=/etc/pam.d/xrdp-sesman
. /usr/share/debconf/confmodule
set -e
case "$1" in
purge)
;;
remove)
TMPFILE=$(mktemp /tmp/sesman.XXXXX)
trap "rm -f $TMPFILE" 0
grep -v uds $SESMANFILE > $TMPFILE # Removes all UDS lines from sesman if they exists
cp $TMPFILE $SESMANFILE
trap "rm -f $TMPFILE" 0
;;
upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "postrm called with unknown argument \`$1'" >&2
exit 1
;;
esac
#DEBHELPER#

View File

@ -1,41 +0,0 @@
#!/usr/bin/make -f
# -*- makefile -*-
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build: build-arch build-indep
build-arch: build-stamp
build-indep: build-stamp
build-stamp: configure-stamp
dh_testdir
$(MAKE)
touch $@
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
dh_clean
install: build
dh_testdir
dh_testroot
dh_prep
dh_installdirs
$(MAKE) DESTDIR=$(CURDIR)/debian/udsactor-xrdp install
binary-arch: build install
# emptyness
binary-indep: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_compress
dh_link
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep
.PHONY: build clean binary-indep binary install configure

View File

@ -1 +0,0 @@
session optional pam_exec.so /usr/bin/uds-sesman

View File

@ -1 +0,0 @@
This package provides the interaction between xrdp and uds

View File

@ -1,13 +0,0 @@
#!/bin/sh
env > /tmp/env.txt
if [ "$PAM_TYPE" = "open_session" ]; then
nohup /usr/bin/udsactor login $PAM_USER &
# Wait in backgroud to TTY to close (close_session is not being invoked right now)
nohup /usr/bin/uds-wait-session &
elif [ "$PAM_TYPE" = "close_session" ]; then
nohup /usr/bin/udsactor logout $PAM_USER &
fi
return 0

View File

@ -1,12 +0,0 @@
#!/bin/sh
while :
do
sleep 5 # Wait 5 seconds between checks
found=`ps -f -u$PAM_USER | grep -v grep | grep -v uds-wait-session | grep "$PAM_TTY" | wc -l`
if [ "$found" = "0" ]; then
/usr/bin/udsactor logout $PAM_USER
exit 0
fi
done

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>USDActorInstaller</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>

View File

@ -1,27 +0,0 @@
Copyright (c) 2012 Virtual Cable S.L.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Virtual Cable S.L. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,188 +0,0 @@
# Auto-generated by EclipseNSIS Script Wizard
# 23-oct-2011 23:38:18
Name "UDS Actor"
# General Symbol Definitions
!define REGKEY "SOFTWARE\$(^Name)"
!define VERSION 1.0
!define COMPANY "Virtual Cable S.L."
!define URL http://www.virtualcable.com
# MultiUser Symbol Definitions
!define MULTIUSER_EXECUTIONLEVEL Admin
!define MULTIUSER_INSTALLMODE_DEFAULT_CURRENTUSER
!define MULTIUSER_INSTALLMODE_COMMANDLINE
!define MULTIUSER_INSTALLMODE_INSTDIR UDSActor
!define MULTIUSER_INSTALLMODE_INSTDIR_REGISTRY_KEY "${REGKEY}"
!define MULTIUSER_INSTALLMODE_INSTDIR_REGISTRY_VALUE "Path"
# MUI Symbol Definitions
!define MUI_ICON "${NSISDIR}\Contrib\Graphics\Icons\orange-install.ico"
!define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_FINISHPAGE_RUN $INSTDIR\udsService.exe
!define MUI_FINISHPAGE_RUN_PARAMETERS -c
!define MUI_UNICON "${NSISDIR}\Contrib\Graphics\Icons\orange-uninstall.ico"
!define MUI_UNFINISHPAGE_NOAUTOCLOSE
!define MUI_LANGDLL_REGISTRY_ROOT HKLM
!define MUI_LANGDLL_REGISTRY_KEY ${REGKEY}
!define MUI_LANGDLL_REGISTRY_VALUENAME InstallerLanguage
# Included files
!include MultiUser.nsh
!include Sections.nsh
!include MUI2.nsh
# Reserved Files
!insertmacro MUI_RESERVEFILE_LANGDLL
# Variables
Var StartMenuGroup
# Installer pages
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE license.txt
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
# Installer languages
!insertmacro MUI_LANGUAGE English
!insertmacro MUI_LANGUAGE Spanish
!insertmacro MUI_LANGUAGE French
!insertmacro MUI_LANGUAGE German
# Installer attributes
OutFile UDSActorSetup.exe
InstallDir UDSActor
CRCCheck on
XPStyle on
ShowInstDetails hide
VIProductVersion 1.0.0.0
VIAddVersionKey /LANG=${LANG_ENGLISH} ProductName "UDS Actor"
VIAddVersionKey /LANG=${LANG_ENGLISH} ProductVersion "${VERSION}"
VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyName "${COMPANY}"
VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyWebsite "${URL}"
VIAddVersionKey /LANG=${LANG_ENGLISH} FileVersion "${VERSION}"
VIAddVersionKey /LANG=${LANG_ENGLISH} FileDescription ""
VIAddVersionKey /LANG=${LANG_ENGLISH} LegalCopyright ""
InstallDirRegKey HKLM "${REGKEY}" Path
ShowUninstDetails show
# Installer sections
Section -Main SEC0000
SetOutPath $INSTDIR
SetOverwrite on
File ..\udsService\bin\Release\CookComputing.XmlRpcV2.dll
File ..\udsService\bin\Release\Interop.EventSystemLib.dll
File ..\udsService\bin\Release\Interop.SensEvents.dll
File ..\udsService\bin\Release\log4net.dll
File ..\udsService\bin\Release\udsgui.dll
File ..\udsService\bin\Release\logging.cfg
File ..\udsService\bin\Release\udsService.exe
File ..\udsService\bin\Release\udsService.exe.config
File ..\udsService\bin\Release\udstools.dll
SetOutPath $INSTDIR\es
File ..\udsService\bin\Release\es\udsgui.resources.dll
SetOutPath $INSTDIR\fr
File ..\udsService\bin\Release\fr\udsgui.resources.dll
SetOutPath $INSTDIR\de
File ..\udsService\bin\Release\de\udsgui.resources.dll
WriteRegStr HKLM "${REGKEY}\Components" Main 1
SectionEnd
Section -post SEC0001
WriteRegStr HKLM "${REGKEY}" Path $INSTDIR
SetOutPath $INSTDIR
WriteUninstaller $INSTDIR\udsuninstall.exe
SetOutPath $SMPROGRAMS\$StartMenuGroup
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\$(^UninstallLink).lnk" $INSTDIR\udsuninstall.exe
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\UDS Actor Configuration.lnk" $INSTDIR\udsService.exe -c
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayName "$(^Name)"
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayVersion "${VERSION}"
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" Publisher "${COMPANY}"
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" URLInfoAbout "${URL}"
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayIcon $INSTDIR\udsuninstall.exe
WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" UninstallString $INSTDIR\udsuninstall.exe
WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoModify 1
WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoRepair 1
nsExec::Exec /OEM "$INSTDIR\udsService.exe -i" # Add service after installation
SectionEnd
# Macro for selecting uninstaller sections
!macro SELECT_UNSECTION SECTION_NAME UNSECTION_ID
Push $R0
ReadRegStr $R0 HKLM "${REGKEY}\Components" "${SECTION_NAME}"
StrCmp $R0 1 0 next${UNSECTION_ID}
!insertmacro SelectSection "${UNSECTION_ID}"
GoTo done${UNSECTION_ID}
next${UNSECTION_ID}:
!insertmacro UnselectSection "${UNSECTION_ID}"
done${UNSECTION_ID}:
Pop $R0
!macroend
# Uninstaller sections
Section /o -un.Main UNSEC0000
nsExec::Exec /OEM "$INSTDIR\udsService.exe -u" # Removes the service prior uninstall :-)
Delete /REBOOTOK $INSTDIR\es\udsgui.resources.dll
Delete /REBOOTOK $INSTDIR\fr\udsgui.resources.dll
Delete /REBOOTOK $INSTDIR\de\udsgui.resources.dll
Delete /REBOOTOK $INSTDIR\udstools.dll
Delete /REBOOTOK $INSTDIR\udsService.exe.config
Delete /REBOOTOK $INSTDIR\udsService.exe
Delete /REBOOTOK $INSTDIR\udsgui.dll
Delete /REBOOTOK $INSTDIR\logging.cfg
Delete /REBOOTOK $INSTDIR\log4net.dll
Delete /REBOOTOK $INSTDIR\Interop.SensEvents.dll
Delete /REBOOTOK $INSTDIR\Interop.EventSystemLib.dll
Delete /REBOOTOK $INSTDIR\CookComputing.XmlRpcV2.dll
DeleteRegValue HKLM "${REGKEY}\Components" Main
SectionEnd
Section -un.post UNSEC0001
DeleteRegKey HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)"
Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\$(^UninstallLink).lnk"
Delete /REBOOTOK $INSTDIR\udsuninstall.exe
DeleteRegValue HKLM "${REGKEY}" Path
DeleteRegKey /IfEmpty HKLM "${REGKEY}\Components"
DeleteRegKey /IfEmpty HKLM "${REGKEY}"
RmDir /REBOOTOK $SMPROGRAMS\$StartMenuGroup
RmDir /REBOOTOK $INSTDIR
SectionEnd
# Installer functions
Function .onInit
InitPluginsDir
StrCpy $StartMenuGroup "Virtual Cable\UDS Actor"
ReadRegDWORD $0 HKLM "SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5" SP
${if} $0 != 1
MessageBox MB_OK "$(^NoDotNet)"
Abort
${EndIf}
!insertmacro MUI_LANGDLL_DISPLAY
!insertmacro MULTIUSER_INIT
FunctionEnd
# Uninstaller functions
Function un.onInit
StrCpy $StartMenuGroup "Virtual Cable\UDS Actor"
!insertmacro MUI_UNGETLANGUAGE
!insertmacro MULTIUSER_UNINIT
!insertmacro SELECT_UNSECTION Main ${UNSEC0000}
FunctionEnd
# Installer Language Strings
LangString ^NoDotNet ${LANG_ENGLISH} ".NET 3.5 sp1 Required.$\nPlease, install it to proceed"
LangString ^NoDotNet ${LANG_SPANISH} "Se requiere .NET 3.5 sp1.$\nPor favor, instalelo para proceder"
LangString ^NoDotNet ${LANG_FRENCH} ".NET Framework 3.5 SP1 requis.$\nVeuillez, installez-le de procéder"
LangString ^NoDotNet ${LANG_GERMAN} "Erforderlich ist. NET 3.5 sp1.$\nPor Bitte installieren Sie es, um fortzufahren"
LangString ^UninstallLink ${LANG_ENGLISH} "Uninstall $(^Name)"
LangString ^UninstallLink ${LANG_SPANISH} "Desinstalar $(^Name)"
LangString ^UninstallLink ${LANG_FRENCH} "Désinstaller $(^Name)"
LangString ^UninstallLink ${LANG_GERMAN} "deinstallieren $(^Name)"

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using CookComputing.XmlRpc;
namespace uds
{
public interface IUDS : IXmlRpcProxy
{
[XmlRpcMethod("test")]
bool Test();
[XmlRpcMethod("message")]
string Message(string id, string message, string data);
}
}

View File

@ -1,89 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
using log4net;
using System.Security.Principal;
namespace uds.Info
{
public class Computer
{
private static ILog logger = LogManager.GetLogger(typeof(Computer));
public struct InterfaceInfo
{
public string ip;
public string mac;
public InterfaceInfo(string _ip, string _mac)
{
ip = _ip; mac = _mac;
}
}
public static List<InterfaceInfo> GetInterfacesInfo()
{
if (NetworkInterface.GetIsNetworkAvailable() == false)
return null;
List<InterfaceInfo> res = new List<InterfaceInfo>();
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
byte[] addr = nic.GetPhysicalAddress().GetAddressBytes();
if (addr.Length != 6)
continue;
IPInterfaceProperties props = nic.GetIPProperties();
List<string> ips = new List<string>();
foreach (IPAddressInformation ip in props.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
ips.Add(ip.Address.ToString());
}
string tmp = nic.GetPhysicalAddress().ToString();
string nc = tmp.Substring(0, 2) + ":" + tmp.Substring(2,2) + ":" + tmp.Substring(4,2) + ":" + tmp.Substring(6,2) + ":" +
tmp.Substring(8,2) + ":" + tmp.Substring(10,2);
res.Add(new InterfaceInfo(string.Join(",", ips.ToArray()), nc));
}
}
return res;
}
public static DomainInfo GetDomainInfo()
{
return new DomainInfo();
}
public static OsInfo GetOsInfo()
{
return new OsInfo();
}
public static bool IsUserAdministrator()
{
//bool value to hold our return value
bool isAdmin;
try
{
//get the currently logged in user
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException)
{
isAdmin = false;
}
catch (Exception)
{
isAdmin = false;
}
return isAdmin;
}
}
}

View File

@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using log4net;
namespace uds.Info
{
public class DomainInfo
{
private static ILog logger = LogManager.GetLogger(typeof(DomainInfo));
// Win32 Result Code Constant
const int ErrorSuccess = 0;
// NetGetJoinInformation() Enumeration
public enum NetJoinStatus
{
NetSetupUnknownStatus = 0,
NetSetupUnjoined,
NetSetupWorkgroupName,
NetSetupDomainName
}
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status);
[DllImport("Netapi32.dll")]
static extern int NetApiBufferFree(IntPtr Buffer);
// Info obtained
private string _computerName;
private string _domainName;
private NetJoinStatus _status;
public DomainInfo()
{
_domainName = "";
_computerName = System.Environment.MachineName;
_status = NetJoinStatus.NetSetupUnknownStatus;
IntPtr pDomain = IntPtr.Zero;
try
{
int result = 0;
result = NetGetJoinInformation(null, out pDomain, out _status);
if (result == ErrorSuccess )
{
if( _status == NetJoinStatus.NetSetupDomainName )
_domainName = Marshal.PtrToStringAuto(pDomain);
}
}
finally
{
if (pDomain != IntPtr.Zero) NetApiBufferFree(pDomain);
}
logger.Debug("Name: " + _computerName + ", Domain: " + _domainName + ", status" + _status.ToString());
}
public string ComputerName
{
get { return _computerName; }
}
public string DomainName
{
get { return _domainName; }
}
public NetJoinStatus Status
{
get { return _status; }
}
}
}

View File

@ -1,111 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
namespace uds.Info
{
public class OsInfo
{
private static ILog logger = LogManager.GetLogger(typeof(OsInfo));
public enum WindowsVersion {
Unknown,
Win95,
Win98,
Win98SE,
WinME,
WinNT351,
WinNT40,
Win2000,
WinXP,
WinVista,
Win7
};
WindowsVersion _version;
string _servicePack;
int _architecture;
public OsInfo()
{
//Get Operating system information.
OperatingSystem os = Environment.OSVersion;
//Get version information about the os.
Version vs = os.Version;
_version = WindowsVersion.Unknown;
_servicePack = os.ServicePack;
_architecture = 0;
if (os.Platform == PlatformID.Win32Windows)
{
//This is a pre-NT version of Windows
switch (vs.Minor)
{
case 0:
_version = WindowsVersion.Win95;
break;
case 10:
if (vs.Revision.ToString() == "2222A")
_version = WindowsVersion.Win98SE;
else
_version = WindowsVersion.Win98;
break;
case 90:
_version = WindowsVersion.WinME;
break;
default:
break;
}
}
else if (os.Platform == PlatformID.Win32NT)
{
switch (vs.Major)
{
case 3:
_version = WindowsVersion.WinNT351;
break;
case 4:
_version = WindowsVersion.WinNT40;
break;
case 5:
if (vs.Minor == 0)
_version = WindowsVersion.Win2000;
else
_version = WindowsVersion.WinXP;
break;
case 6:
if (vs.Minor == 0)
_version = WindowsVersion.WinVista;
else
_version = WindowsVersion.Win7;
break;
default:
break;
}
}
//Make sure we actually got something in our OS check
//We don't want to just return " Service Pack 2" or " 32-bit"
//That information is useless without the OS version.
if (_version != WindowsVersion.Unknown)
{
//Append the OS architecture. i.e. "Windows XP Service Pack 3 32-bit"
_architecture = getOSArchitecture();
}
}
private static int getOSArchitecture()
{
string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
Console.WriteLine("Arch: " + pa);
return ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? 32 : 64);
}
public WindowsVersion Version
{
get { return _version; }
}
}
}

View File

@ -1,271 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Runtime.InteropServices;
using System.Threading;
namespace uds
{
public class Operation
{
private static ILog logger = LogManager.GetLogger(typeof(Operation));
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
const uint FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
const uint FORMAT_MESSAGE_FROM_STRING = 0x00000400;
[DllImport("Kernel32.dll", SetLastError = true)]
static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer,
uint nSize, IntPtr pArguments);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst,
int len, IntPtr prev, IntPtr relen);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool ExitWindowsEx(int flg, int rea);
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall,
SetLastError = true)]
static extern uint NetUserChangePassword(
[MarshalAs(UnmanagedType.LPWStr)] string domainname,
[MarshalAs(UnmanagedType.LPWStr)] string username,
[MarshalAs(UnmanagedType.LPWStr)] string oldpassword,
[MarshalAs(UnmanagedType.LPWStr)] string newpassword
);
[Flags]
public enum JoinOptions
{
NETSETUP_JOIN_DOMAIN = 0x00000001,
NETSETUP_ACCT_CREATE = 0x00000002,
NETSETUP_ACCT_DELETE = 0x00000004,
NETSETUP_WIN9X_UPGRADE = 0x00000010,
NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020,
NETSETUP_JOIN_UNSECURE = 0x00000040,
NETSETUP_MACHINE_PWD_PASSED = 0x00000080,
NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400,
NETSETUP_DEFER_SPN_SET = 0x10000000
}
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError=true)]
static extern uint NetJoinDomain(string lpServer, string lpDomain, string lpAccountOU, string lpAccount, string lpPassword, JoinOptions NameType);
enum COMPUTER_NAME_FORMAT
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified,
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
static extern bool SetComputerNameEx(COMPUTER_NAME_FORMAT NameType, string lpBuffer);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const string SE_SECURITY_NAME = "SeSecurityPrivilege";
internal const string SE_TCB_NAME = "SeTcbPrivilege";
public const int EWX_LOGOFF = 0x00000000;
public const int EWX_SHUTDOWN = 0x00000001;
public const int EWX_REBOOT = 0x00000002;
public const int EWX_FORCE = 0x00000004;
public const int EWX_POWEROFF = 0x00000008;
public const int EWX_FORCEIFHUNG = 0x00000010;
public static bool Reboot(int flg = EWX_FORCEIFHUNG|EWX_REBOOT)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
logger.Debug("Result: " + ok.ToString());
if (ok)
logger.Info("Rebooting computer");
else
logger.Error("Could not reboot machine. (Error " + ok.ToString() + ")");
return ok;
}
private static bool waitAfterError(string op, bool useGetLastError, ManualResetEvent waitEvent, TimeSpan retryDelay)
{
if (useGetLastError)
logger.Error("Error at " + op + ": " + GetLastErrorStr() + ". Retrying in " + retryDelay.Seconds.ToString() + " secs");
else
logger.Error("Error at " + op + ". Retrying in " + retryDelay.Seconds.ToString() + " secs");
if (waitEvent.WaitOne(retryDelay))
return false;
return true;
}
public static bool RenameComputer(string newName)
{
logger.Info("Renaming computer to \"" + newName + "\"");
try
{
return SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname, newName);
}
catch (Exception)
{
return false;
}
}
public static bool RenameComputer(string newName, ManualResetEvent waitEvent, TimeSpan retryDelay)
{
while (RenameComputer(newName) == false)
{
if (waitAfterError("Rename", true, waitEvent, retryDelay) == false)
return false;
}
return true;
}
public static bool JoinDomain(string domain, string ou, string account, string password, bool oneStep = false)
{
if (account.Contains('@') == false && account.Contains('\\') == false)
{
if (domain.Contains('.'))
account = account + "@" + domain;
else
account = domain + "\\" + account;
}
logger.Info("Joining domain: \"" + domain + "\", \"" + ou + "\", \"" + account + "\", \"" + "*****" + "\"" + ", oneStep = " + oneStep.ToString());
// Flag NETSETUP_JOIN_WITH_NEW_NAME not supported on win xp/2000
JoinOptions flags = JoinOptions.NETSETUP_ACCT_CREATE | JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED | JoinOptions.NETSETUP_JOIN_DOMAIN;
if (oneStep)
flags |= JoinOptions.NETSETUP_JOIN_WITH_NEW_NAME;
if (ou == "")
ou = null;
try
{
uint res = NetJoinDomain(null, domain, ou, account, password, flags);
if (res == 2224)
{
flags = JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED | JoinOptions.NETSETUP_JOIN_DOMAIN;
logger.Info("Existing account for machine found, reusing it");
res = NetJoinDomain(null, domain, null, account, password, flags);
}
if (res != 0)
{
logger.Error("Error joining domain:" + GetLastErrorStr((int)res));
}
else
logger.Info("Successfully joined domain");
logger.Debug("Result of join: " + res);
return res == 0;
}
catch (Exception e)
{
logger.Error("Exception at join domain", e);
return false;
}
}
public static bool JoinDomain(string domain, string ou, string account, string password, bool oneStep, ManualResetEvent waitEvent, TimeSpan retryDelay)
{
while (JoinDomain(domain, ou, account, password, oneStep) == false)
{
if (waitAfterError("Join domain", true, waitEvent, retryDelay) == false)
return false;
}
return true;
}
public static bool ChangeUserPassword(string user, string oldPass, string newPass)
{
try {
logger.Debug("Setting new password for user " + user + " to " + newPass);
Info.DomainInfo info = Info.Computer.GetDomainInfo();
uint res = NetUserChangePassword(info.ComputerName, user, oldPass, newPass);
logger.Debug("Result of changeUserPassword: " + res);
if( res != 0 )
logger.Error("Could not change password for user \"" + user + "\" (using password \"" + newPass + "\") at \"" + info.ComputerName + "\", result: " + res);
return res == 0;
}
catch (Exception e)
{
logger.Error("Exception at change user password", e);
return false;
}
}
private static string GetLastErrorStr(int nLastError=-1)
{
if(nLastError == -1)
nLastError = Marshal.GetLastWin32Error();
IntPtr lpMsgBuf = IntPtr.Zero;
uint dwChars = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero,
(uint)nLastError,
0, // Default language
ref lpMsgBuf,
0,
IntPtr.Zero);
if (dwChars == 0)
{
return "(unknown)";
}
string sRet = Marshal.PtrToStringAnsi(lpMsgBuf);
// Free the buffer.
lpMsgBuf = LocalFree(lpMsgBuf);
return sRet;
}
}
}

View File

@ -1,38 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("rpc")]
[assembly: AssemblyDescription("RPC Connection Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Virtual Cable S.L.")]
[assembly: AssemblyProduct("UDS Service")]
[assembly: AssemblyCopyright("Copyright © Virtual Cable S.L. 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("381689d6-aaf1-45b2-b6c5-065184bc7f80")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión
// mediante el asterisco ('*'), como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]

View File

@ -1,73 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
namespace uds
{
public class config
{
private static ILog logger = LogManager.GetLogger(typeof(config));
public static string broker = "";
public static bool ssl = true;
public static int timeOut = 10;
// Constants
private const string KEY_SOFTWARE = "Software";
private const string KEY_VCABLE = "Virtual Cable S.L.";
private const string KEY_UDSACTOR = "UDS Actor";
private const string VALUE_BROKER = "server";
private const string VALUE_SSL = "secured";
private const string VALUE_TIMEOUT = "timeout";
public static void LoadConfig()
{
Microsoft.Win32.RegistryKey software = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(KEY_SOFTWARE);
Microsoft.Win32.RegistryKey vcable = software.OpenSubKey(KEY_VCABLE);
// Default values if registry don't exists
if( vcable == null )
return;
Microsoft.Win32.RegistryKey udssactor = vcable.OpenSubKey(KEY_UDSACTOR);
// Default values if registry don't exists
if (udssactor == null)
return;
broker = (string)udssactor.GetValue(VALUE_BROKER, "");
string tmp = (string)udssactor.GetValue(VALUE_SSL, "1");
ssl = (tmp == "1") ? true : false;
tmp = (string)udssactor.GetValue(VALUE_TIMEOUT, "10");
try { timeOut = Int32.Parse(tmp); }
catch (Exception) { timeOut = 10; }
}
public static void SaveConfig()
{
Microsoft.Win32.RegistryKey software = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(KEY_SOFTWARE, true);
Microsoft.Win32.RegistryKey vcable = software.OpenSubKey(KEY_VCABLE, true);
if (vcable == null)
{
// Tries to create subkey
vcable = software.CreateSubKey(KEY_VCABLE);
if (vcable == null)
throw new InvalidOperationException("Can't access registry!!! " + KEY_VCABLE);
}
Microsoft.Win32.RegistryKey udssactor = vcable.OpenSubKey(KEY_UDSACTOR, true);
if (udssactor == null)
{
// Tries to create subkey
udssactor = vcable.CreateSubKey(KEY_UDSACTOR);
if (udssactor == null)
throw new InvalidOperationException("Can't access registry!!! " + KEY_UDSACTOR);
}
udssactor.SetValue(VALUE_BROKER, broker);
udssactor.SetValue(VALUE_SSL, ssl ? "1" : "0");
udssactor.SetValue(VALUE_TIMEOUT, timeOut.ToString());
}
}
}

View File

@ -1,234 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using CookComputing.XmlRpc;
using log4net;
namespace uds
{
public class rpc
{
private static ILog logger = LogManager.GetLogger(typeof(rpc));
private static rpc _manager = null;
private static bool _unlocked = false;
private string _id = null;
private IUDS service = null;
private const string LOGON_MSG = "logon";
private const string LOGOFF_MSG = "logoff";
private const string INFO_MSG = "information";
private const string READY_MSG = "ready";
private const string IP_MSG = "ip";
private const string LOG_MSG = "log";
private rpc(string url)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
logger.Debug("Initializing rpc at \"" + url + "\" with timeout of " + config.timeOut.ToString());
_id = null;
service = XmlRpcProxyGen.Create<IUDS>();
service.Timeout = config.timeOut * 1000;
service.Url = url;
}
public static void Initialize(string broker, bool useSSl)
{
if (!_unlocked)
throw new Exception("access denied");
_manager = null; // Release previous manager
string protocol = useSSl ? "https" : "http";
_manager = new rpc(protocol + "://" + broker + "/xmlrpc");
}
public static void Unlock(string pass)
{
if( pass == string.Join("", new string[] {"m","a","m","0" } ) )
_unlocked = true;
}
public static rpc Manager
{
get { return _manager; }
}
private static string Unscramble(string str)
{
if( str == "" || str == null )
return str;
StringBuilder sb = new StringBuilder();
int val = 0x32;
for (int i = 0; i < str.Length; i += 2)
{
int c = Int32.Parse(str.Substring(i, 2), System.Globalization.NumberStyles.HexNumber) ^ val;
val = (val + c) & 0xFF;
sb.Insert(0, Convert.ToString(Convert.ToChar(c)));
}
return sb.ToString();
}
public bool Test()
{
try
{
logger.Debug("Invoking service test");
service.Test();
}
catch (Exception e)
{
logger.Debug("Exception", e);
return false;
}
return true;
}
public string Message(string message, string data)
{
if (_id == null)
{
logger.Debug("The id is null, recreating id");
List<Info.Computer.InterfaceInfo> interfaces = Info.Computer.GetInterfacesInfo();
_id = string.Join(",", interfaces.ConvertAll<String>(i => i.mac).ToArray());
logger.Debug("The id is now " + _id);
}
logger.Debug("Sending message to broker: " + _id + ", " + message + ", " + data);
string ret = Unscramble(service.Message(_id, message, data));
logger.Debug("Returned value: " + ret);
return ret;
}
public static string[] Logon(string username)
{
if (rpc.Manager != null)
{
logger.Info("Invoking remote logon of user " + username);
try
{
return rpc.Manager.Message(LOGON_MSG, username).Split('\t');
}
catch (Exception)
{
logger.Fatal("Could cont contact broker at " + rpc.Manager.service.Url);
return new string[0];
}
}
logger.Debug("Remote logon not invoked. RPC Disabled");
return new string[0];
}
public static void Logoff(string username)
{
if (rpc.Manager != null)
{
logger.Debug("Invoking remote logoff of user " + username);
try
{
rpc.Manager.Message(LOGOFF_MSG, username);
}
catch (Exception)
{
logger.Info("Could cont contact broker at " + rpc.Manager.service.Url);
}
}
else
{
logger.Debug("Remote logoff not invoked. RPC Disabled");
}
}
public static string GetInfo()
{
string res = null;
if (rpc.Manager != null)
{
logger.Debug("Invoking remote GetInfo");
try
{
res = rpc.Manager.Message(INFO_MSG, "");
}
catch (Exception)
{
res = null;
}
}
return res;
}
public static bool SetReady()
{
bool ok = false;
if (rpc.Manager != null)
{
logger.Info("Machine is Ready");
try
{
List<Info.Computer.InterfaceInfo> interfaces = Info.Computer.GetInterfacesInfo();
string info = string.Join(",", interfaces.ConvertAll<String>(i => i.mac + "=" + i.ip).ToArray());
rpc.Manager.Message(READY_MSG, info);
ok = true;
}
catch (Exception)
{
}
}
return ok;
}
public static bool NotifyIPChange()
{
bool ok = false;
if (rpc.Manager != null)
{
logger.Debug("Informing broker of ip change");
try
{
List<Info.Computer.InterfaceInfo> interfaces = Info.Computer.GetInterfacesInfo();
string info = string.Join(",", interfaces.ConvertAll<String>(i => i.mac + "=" + i.ip).ToArray());
rpc.Manager.Message(IP_MSG, info);
ok = true;
}
catch (Exception)
{
}
}
return ok;
}
public static void Log(string msg, string Level)
{
if (rpc.Manager != null)
{
logger.Debug("Sending message " + msg + " of level " + Level);
rpc.Manager.Message(LOG_MSG, string.Join("\t", new string[] { msg, Level }));
}
}
public static void FlushLoggers()
{
log4net.Repository.ILoggerRepository rep = LogManager.GetRepository();
foreach (log4net.Appender.IAppender appender in rep.GetAppenders())
{
var buffered = appender as log4net.Appender.BufferingAppenderSkeleton;
if (buffered != null)
buffered.Flush();
}
}
public static void ResetId()
{
logger.Debug("Reseting ID of rpc");
FlushLoggers();
if (rpc.Manager != null)
rpc.Manager._id = null;
}
public static void ResetManager()
{
logger.Debug("Disabling rpc");
FlushLoggers();
rpc._manager = null;
}
}
}

View File

@ -1,88 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{9861A89C-7007-4A42-8BEB-9914BCF5524C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>uds</RootNamespace>
<AssemblyName>udstools</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>true</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>true</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<ItemGroup>
<Reference Include="CookComputing.XmlRpcV2">
<HintPath>..\xmlrpc\CookComputing.XmlRpcV2.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\log4net\3.5\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="config.cs" />
<Compile Include="Info\Computer.cs" />
<Compile Include="Info\DomainInfo.cs" />
<Compile Include="Info\OsInfo.cs" />
<Compile Include="IUDS.cs" />
<Compile Include="Operation.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="rpc.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -1,66 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "udsService", "udsService\udsService.csproj", "{E528C884-A7FA-401F-AE2E-C1796D326461}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "udsgui", "udsgui\udsgui.csproj", "{278F54DB-771A-4EF2-BEF2-9447F988303F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tools", "rpc\tools.csproj", "{9861A89C-7007-4A42-8BEB-9914BCF5524C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|Any CPU.ActiveCfg = Debug|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|Mixed Platforms.ActiveCfg = Debug|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|Mixed Platforms.Build.0 = Debug|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|x64.ActiveCfg = Debug|x86
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|x64.Build.0 = Debug|x86
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|x86.ActiveCfg = Debug|x86
{E528C884-A7FA-401F-AE2E-C1796D326461}.Debug|x86.Build.0 = Debug|x86
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|Any CPU.ActiveCfg = Release|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|Mixed Platforms.ActiveCfg = Release|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|Mixed Platforms.Build.0 = Release|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|x64.ActiveCfg = Release|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|x64.Build.0 = Release|x64
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|x86.ActiveCfg = Release|x86
{E528C884-A7FA-401F-AE2E-C1796D326461}.Release|x86.Build.0 = Release|x86
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|x64.ActiveCfg = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Debug|x86.ActiveCfg = Debug|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|Any CPU.Build.0 = Release|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|x64.ActiveCfg = Release|Any CPU
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|x86.ActiveCfg = Release|x86
{278F54DB-771A-4EF2-BEF2-9447F988303F}.Release|x86.Build.0 = Release|x86
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|x64.ActiveCfg = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Debug|x86.ActiveCfg = Debug|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|Any CPU.Build.0 = Release|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|x64.ActiveCfg = Release|Any CPU
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|x86.ActiveCfg = Release|x86
{9861A89C-7007-4A42-8BEB-9914BCF5524C}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -1,89 +0,0 @@
using System;
using System.Collections.Generic;
using log4net;
using System.ServiceProcess;
using System.Diagnostics;
using System.Linq;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace uds.Services
{
class Application
{
private static ILog logger = LogManager.GetLogger(typeof(Application));
private const string serviceName = "UDSService";
private const string serviceDisplayName = "UDS Actor";
private const string serviceDescription = "UDS coordination actor";
private const string serviceDependencies = "SENS\0COMSysApp";
private const bool serviceStartOnInstall = false;
/*private static void SensLogon_DisplayLock(string userName)
{
Console.WriteLine("Screen Locked: " + userName);
}
private static void SensLogon_DisplayUnlock(string userName)
{
Console.WriteLine("Screen Unlocked: " + userName);
}*/
private static void InstallService()
{
if (ServiceInstaller.InstallService(System.Reflection.Assembly.GetEntryAssembly().Location, serviceName, serviceDisplayName, serviceDescription, serviceDependencies, serviceStartOnInstall) == false)
{
Console.WriteLine("Can't install service!!!");
}
}
private static void UninstallService()
{
if (ServiceInstaller.UnInstallService("UDSService") == false)
{
Console.WriteLine("Can't uninstall service!!!");
}
}
static void Main(string[] args)
{
logger.Debug("UDS Actor Started");
config.LoadConfig(); // Loads configuration...
// unlocks rpc
rpc.Unlock(string.Join("", new string[] { "m", "a", "m", "0" }));
if (args.Length == 1)
{
switch (args[0])
{
case "-I":
case "-i":
case "/i":
InstallService();
return;
case "-U":
case "-u":
case "/u":
UninstallService();
return;
case "-C":
case "-c":
case "/c":
gui.gui.ShowConfig();
return;
case "-R":
case "-r":
case "/r":
//Operation.Reboot();
return;
case "-h":
case "-H":
default:
Console.WriteLine("Usage: udsService.exe [-i|-u|-h|-c]");
return;
}
}
ServiceBase.Run(new Service());
}
}
}

View File

@ -1,40 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("UDSService")]
[assembly: AssemblyDescription("Service controling the windows's actor of UDS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Virtual Cable S.L.")]
[assembly: AssemblyProduct("USD Actor")]
[assembly: AssemblyCopyright("Copyright © Virtual Cable S.L. 2011")]
[assembly: AssemblyTrademark("UDS")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("73b2a3ab-22c7-4210-8a56-7ee5531ba482")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión
// mediante el asterisco ('*'), como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
//[assembly: log4net.Config.XmlConfigurator()]
[assembly: NeutralResourcesLanguageAttribute("en")]

View File

@ -1,31 +0,0 @@
using System;
using System.Collections.Generic;
using log4net;
namespace uds
{
public class RPCAppender : log4net.Appender.AppenderSkeleton
{
/// <summary>
/// Sends the logging event to UDS
/// </summary>
override protected void Append(log4net.Core.LoggingEvent lEvent)
{
string message = RenderLoggingEvent(lEvent);
// Filters out messages that are FATAL or DEBUG
if (lEvent.Level == log4net.Core.Level.Critical || lEvent.Level == log4net.Core.Level.Fatal || lEvent.Level == log4net.Core.Level.Debug)
return;
rpc.Log(message, lEvent.Level.Name);
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
override protected bool RequiresLayout
{
get { return true; }
}
}
}

View File

@ -1,334 +0,0 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using EventSystemLib;
using System;
using SensEvents;
using log4net;
namespace uds.Services.Sens
{
//In the ManagesSENS namespace
[ComImport, Guid("4E14FBA2-2E22-11D1-9964-00C04FBBB345")]
class EventSystem { }
[ComImport, Guid("7542E960-79C7-11D1-88F9-0080C7D771BF")]
class EventSubcription { }
[ComImport, Guid("AB944620-79C6-11d1-88F9-0080C7D771BF")]
class EventPublisher { }
[ComImport, Guid("cdbec9c0-7a68-11d1-88f9-0080c7d771bf")]
class EventClass { }
class EventSystemRegistrar
{
private static ILog logger = LogManager.GetLogger(typeof(EventSystemRegistrar));
private const string PROGID_EventSubscription = "EventSystem.EventSubscription";
static EventSystemRegistrar() { }
private static IEventSystem es = null;
private static IEventSystem EventSystem
{
get
{
if (es == null)
es = new EventSystem() as IEventSystem;
return es;
}
}
public static void SubscribeToEvents(string description, string subscriptionName, string
subscriptionID, object subscribingObject, Type subscribingType)
{
// activate subscriber
try
{
//create and populate a subscription object
IEventSubscription sub = new EventSubcription() as IEventSubscription;
sub.Description = description;
sub.SubscriptionName = subscriptionName;
sub.SubscriptionID = subscriptionID;
//Get the GUID from the ISensLogon interface
sub.InterfaceID = GetInterfaceGuid(subscribingType);
sub.SubscriberInterface = subscribingObject;
//Store the actual Event.
EventSystem.Store(PROGID_EventSubscription, sub);
}
catch (Exception ex)
{
logger.Error("Exception cauthg subscribing to SENS events: ", ex);
}
}
private static string GetInterfaceGuid(Type theType)
{
object[] attributes = theType.GetCustomAttributes(typeof(GuidAttribute), true);
if (attributes.Length > 0)
{
return "{" + ((GuidAttribute)attributes[0]).Value + "}";
}
else
{
logger.Error("GuidedAttribute not present on the type");
throw new ArgumentException("GuidAttribute not present on the Type.", "theType");
}
}
public static void UnsubscribeToEvents(string subscriptionID)
{
try
{
string strCriteria = "SubscriptionID == " + subscriptionID;
int errorIndex = 0;
EventSystem.Remove("EventSystem.EventSubscription", strCriteria, out errorIndex);
}
catch (Exception ex)
{
logger.Error("Exception cauthg unsubscribing to SENS events: ", ex);
}
}
}
public delegate void SensLogonEventHandler(string userName);
public class SensLogon
{
private static ILog logger = LogManager.GetLogger(typeof(SensLogon));
private static SensLogonInterop eventCatcher;
static SensLogon() { }
private class SensLogonInterop : ISensLogon, IDisposable
{
private static ILog logger = LogManager.GetLogger(typeof(SensLogonInterop));
private const string SubscriptionViewerName = "ManagedSENS.SensLogonInterop";
// generate a subscriptionID
private static string SubscriptionViewerID = "{" + typeof(SensLogonInterop).GUID.ToString().ToUpper() + "}";
private const string SubscriptionViewerDesc = "ManagedSENS Event Subscriber";
private bool registered;
public SensLogonInterop()
{
registered = false;
EventSystemRegistrar.SubscribeToEvents(SubscriptionViewerDesc, SubscriptionViewerName,
SubscriptionViewerID, this, typeof(ISensLogon));
registered = true;
logger.Debug("Sens registered");
}
~SensLogonInterop()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
}
protected void Dispose(bool isExplicit)
{
this.Deactivate();
}
private void Deactivate()
{
if (registered)
{
EventSystemRegistrar.UnsubscribeToEvents(SubscriptionViewerID);
registered = false;
logger.Debug("Sens unregistered");
}
}
public void DisplayLock(string bstrUserName)
{
logger.Debug("SENS Displaylock invoked for user " + bstrUserName);
SensLogon.OnDisplayLock(bstrUserName);
}
public void DisplayUnlock(string bstrUserName)
{
logger.Debug("SENS DisplayUnloock invoked for user " + bstrUserName);
SensLogon.OnDisplayUnlock(bstrUserName);
}
public void Logoff(string bstrUserName)
{
logger.Debug("SENS Logoff invoked for user " + bstrUserName);
SensLogon.OnLogoff(bstrUserName);
}
public void Logon(string bstrUserName)
{
logger.Debug("SENS Logon invoked for user " + bstrUserName);
SensLogon.OnLogon(bstrUserName);
}
public void StartScreenSaver(string bstrUserName)
{
logger.Debug("SENS StartScreenSaver invoked for user " + bstrUserName);
SensLogon.OnStartScreenSaver(bstrUserName);
}
public void StartShell(string bstrUserName)
{
logger.Debug("SENS StartShell invoked for user " + bstrUserName);
SensLogon.OnStartShell(bstrUserName);
}
public void StopScreenSaver(string bstrUserName)
{
logger.Debug("SENS StopScreenSaver invoked for user " + bstrUserName);
SensLogon.OnStopScreenSaver(bstrUserName);
}
}
private static int registerCount = 0;
private static bool IsRegistered
{
get
{
return (registerCount > 0);
}
}
private static SensLogonEventHandler RegisterEvent(SensLogonEventHandler original,
SensLogonEventHandler newDel)
{
bool shouldRegister = (original == null);
original = original + newDel;
if (shouldRegister)
{
if (registerCount <= 0)
{
if (SensLogon.eventCatcher == null)
SensLogon.eventCatcher = new SensLogonInterop();
registerCount = 1;
}
else
{
//Just count them.
registerCount++;
}
}
return original;
}
private static SensLogonEventHandler UnregisterEvent(SensLogonEventHandler original,
SensLogonEventHandler oldDel)
{
original = original - oldDel;
if (original == null)
{
registerCount--;
if (registerCount == 0)
{
//unregister for those events.
SensLogon.eventCatcher.Dispose();
SensLogon.eventCatcher = null;
}
}
return original;
}
private static void exec(string name, SensLogonEventHandler ev, string bStrUsername)
{
if (ev != null)
{
try
{
logger.Debug("Executing " + name + " for user " + bStrUsername );
ev(bStrUsername);
}
catch (Exception ex)
{
logger.Error("Exception cauthg executing sens event " + name, ex);
}
}
}
protected static void OnDisplayLock(string bstrUserName)
{
exec("DisplayLock", SensLogon.displayLock, bstrUserName);
}
protected static void OnDisplayUnlock(string bstrUserName)
{
exec("DisplayUnlock", SensLogon.displayUnlock, bstrUserName);
}
protected static void OnLogoff(string bstrUserName)
{
exec("Logoff", SensLogon.logoff, bstrUserName);
}
protected static void OnLogon(string bstrUserName)
{
exec("Logon", SensLogon.logon, bstrUserName);
}
protected static void OnStartScreenSaver(string bstrUserName)
{
exec("StartScreenSaver", SensLogon.startScreenSaver, bstrUserName);
}
protected static void OnStartShell(string bstrUserName)
{
exec("Startshell", SensLogon.startShell, bstrUserName);
}
protected static void OnStopScreenSaver(string bstrUserName)
{
exec("StopScreenSaver", SensLogon.stopScreenSaver, bstrUserName);
}
private static SensLogonEventHandler displayLock = null;
private static SensLogonEventHandler displayUnlock = null;
private static SensLogonEventHandler logoff = null;
private static SensLogonEventHandler logon = null;
private static SensLogonEventHandler startScreenSaver = null;
private static SensLogonEventHandler startShell = null;
private static SensLogonEventHandler stopScreenSaver = null;
public static event SensLogonEventHandler DisplayLock
{
add { SensLogon.displayLock = SensLogon.RegisterEvent(SensLogon.displayLock, value); }
remove { SensLogon.displayLock = SensLogon.UnregisterEvent(SensLogon.displayLock, value); }
}
public static event SensLogonEventHandler DisplayUnlock
{
add { SensLogon.displayUnlock = SensLogon.RegisterEvent(SensLogon.displayUnlock, value); }
remove { SensLogon.displayUnlock = SensLogon.UnregisterEvent(SensLogon.displayUnlock, value); }
}
public static event SensLogonEventHandler Logoff
{
add { SensLogon.logoff = SensLogon.RegisterEvent(SensLogon.logoff, value); }
remove { SensLogon.logoff = SensLogon.UnregisterEvent(SensLogon.logoff, value); }
}
public static event SensLogonEventHandler Logon
{
add { SensLogon.logon = SensLogon.RegisterEvent(SensLogon.logon, value); }
remove { SensLogon.logon = SensLogon.UnregisterEvent(SensLogon.logon, value); }
}
public static event SensLogonEventHandler StartScreenSaver
{
add { SensLogon.startScreenSaver = SensLogon.RegisterEvent(SensLogon.startScreenSaver, value); }
remove { SensLogon.startScreenSaver = SensLogon.UnregisterEvent(SensLogon.startScreenSaver, value); }
}
public static event SensLogonEventHandler StartShell
{
add { SensLogon.startShell = SensLogon.RegisterEvent(SensLogon.startShell, value); }
remove { SensLogon.startShell = SensLogon.UnregisterEvent(SensLogon.startShell, value); }
}
public static event SensLogonEventHandler StopScreenSaver
{
add { SensLogon.stopScreenSaver = SensLogon.RegisterEvent(SensLogon.stopScreenSaver, value); }
remove { SensLogon.stopScreenSaver = SensLogon.UnregisterEvent(SensLogon.stopScreenSaver, value); }
}
}
}

View File

@ -1,419 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using log4net;
namespace uds.Services
{
public class Service : System.ServiceProcess.ServiceBase
{
private static ILog logger = LogManager.GetLogger(typeof(Service));
const int secsDelay = 5;
const int retrySecsDelay = 60;
private Thread _thread;
private ManualResetEvent _stopEvent;
private TimeSpan _delay;
private TimeSpan _retryDelay;
private bool _reboot;
private static void SensLogon_Logon(string userName)
{
logger.Info("User " + userName + " has logged in");
string[] data = rpc.Logon(userName);
if (data.Length == 2)
{
try
{
string WindowsDir = Environment.GetEnvironmentVariable("windir");
System.IO.TextWriter file = new System.IO.StreamWriter(WindowsDir + "\\remoteh.txt", false);
file.Write(data[1]);
file.Close();
file = new System.IO.StreamWriter(WindowsDir + "\\remoteip.txt", false);
file.Write(data[0]);
file.Close();
}
catch (Exception e)
{
logger.Error("Remote information could not be saved", e);
// But this continues...
}
}
else
{
logger.Error("Invalid data received at Logon notification: " + string.Join(",", data));
}
}
private static void SensLogon_Logout(string userName)
{
logger.Info("User " + userName + " has logged out");
rpc.Logoff(userName);
}
private static void SensLogon_DisplayLock(string username)
{
logger.Info("User " + username + " has locked the display");
}
private static void SensLogon_DisplayUnlock(string username)
{
logger.Info("User " + username + " has unlocked the display");
}
public Service()
{
ServiceName = "UDS Actor";
_thread = null;
_stopEvent = null;
_delay = new TimeSpan(0, 0, 0, secsDelay, 0);
_retryDelay = new TimeSpan(0, 0, 0, retrySecsDelay, 0);
_reboot = false;
}
protected override void OnStart(string[] args)
{
logger.Debug("Initiated OnStart of service");
ThreadStart start = new ThreadStart(this.ParallelThread);
_thread = new Thread(start);
_stopEvent = new ManualResetEvent(false);
(_thread).Start();
// Prepare SENS events
Sens.SensLogon.Logon += SensLogon_Logon;
Sens.SensLogon.Logoff += SensLogon_Logout;
Sens.SensLogon.DisplayLock += SensLogon_DisplayLock;
Sens.SensLogon.DisplayUnlock += SensLogon_DisplayUnlock;
logger.Debug("Invoking base OnStart");
// Invoke base OnStart
base.OnStart(args);
}
protected override void OnStop()
{
logger.Debug("Initiated service shutdown");
// Signal thread if already running
_stopEvent.Set();
// Prepare SENS events
Sens.SensLogon.DisplayUnlock -= SensLogon_DisplayUnlock;
Sens.SensLogon.DisplayLock -= SensLogon_DisplayLock;
Sens.SensLogon.Logoff -= SensLogon_Logout;
Sens.SensLogon.Logon -= SensLogon_Logon;
_thread.Join((2 + secsDelay) * 1000);
base.OnStop();
}
private void ParallelThread()
{
logger.Debug("Initiated Service main");
Dictionary<string, string> knownIps = new Dictionary<string, string>();
try
{
// We have to wait till we have ip
List<Info.Computer.InterfaceInfo> interfaces = null;
while (interfaces == null)
{
logger.Debug("Trying to get network info..");
try
{
interfaces = Info.Computer.GetInterfacesInfo();
}
catch (Exception e)
{
logger.Error("Exception!!!", e);
}
if (interfaces == null)
{
bool exit = _stopEvent.WaitOne(_delay);
if (exit)
{
logger.Debug("Exit requested waiting for interfaces");
return;
}
}
}
// We have now interfaces info, intialize the connection and try to connect
// In fact, we do not use the interfaces received except for logging, initialize gets their own data from there
rpc.Initialize(config.broker, config.ssl);
logger.Info("Interfaces: " + string.Join(",", interfaces.ConvertAll<String>(i => i.mac + "=" + i.ip).ToArray()));
string action = null;
while (action == null)
{
logger.Debug("Trying to contact server to get action");
rpc.ResetId(); // So we get interfaces info every time we try to contact broker
action = rpc.GetInfo(); // Get action to execute
if (action == null)
{
bool exit = _stopEvent.WaitOne(_delay);
if (exit)
{
logger.Debug("Exit requested waiting for broker info");
return;
}
}
}
if (action == "")
{
logger.Debug("Unmanaged machine, exiting...");
// Reset rpc so next calls are simply ignored...
rpc.ResetManager();
return;
}
// Important note:
// Remove ":" as separator, due to the posibility that ":" can be used as part of a password
// Old ":" is now '\r'
// In order to keep compatibility, getInfo will invoke rcp "information", so old actors "versions"
// will keep invoking "info" and return the old ":" separator way
// Message is in the form "action\rparams", where we can identify:
// rename\rcomputername --- > Just rename
// rename\rcomputername\tuser\toldPass\tnewPass --> Rename with user password changing
// domain:computername\tdomain\tou\tuserToAuth\tpassToAuth --> Rename and add machine to domain
string[] data = action.Split('\r');
if (data.Length != 2)
{
logger.Error("Unrecognized instruction: \"" + action + "\"");
rpc.ResetManager(); // Invalidates manager, cause we don't recognized it
return;
}
string[] parms = data[1].Split('\t');
switch (data[0])
{
case "rename":
if (parms.Length == 1)
// Do not have to change user password
Rename(parms[0], null, null, null);
else if (parms.Length == 4)
// Rename, and also change user password
Rename(parms[0], parms[1], parms[2], parms[3]);
else
{
logger.Error("Unrecognized parameters: " + data[1]);
rpc.ResetManager();
return;
}
break;
case "domain":
{
if (parms.Length != 5)
{
logger.Error("Unrecognized parameters: " + data[1]);
rpc.ResetManager(); // Invalidates manager, cause we don't recognized it
return;
}
JoinDomain(parms[0], parms[1], parms[2], parms[3], parms[4]);
}
break;
default:
logger.Error("Unrecognized action: \"" + data[0] + "\"");
rpc.ResetManager(); // Invalidates manager, cause we don't recognized it
return;
}
// Reboot process or no process at all, exit
if (_reboot || rpc.Manager == null)
{
logger.Debug("Returning, reboot = '" + _reboot.ToString() + "' + rcp.Manager = '" + rpc.Manager.ToString() + "'");
return;
}
logger.Debug("Main loop waiting for ip change");
// Now, every secs delay, get if the interfaces ips changes and notify service
try
{
foreach (Info.Computer.InterfaceInfo i in Info.Computer.GetInterfacesInfo())
knownIps.Add(i.mac, i.ip);
}
catch (Exception e)
{
logger.Error("Could not accesss ip adresses!!", e);
return;
}
}
catch (Exception e)
{
logger.Error(e);
}
while (true)
{
try
{
foreach (Info.Computer.InterfaceInfo i in Info.Computer.GetInterfacesInfo())
{
/*logger.Debug(knownIps.ContainsKey(i.mac));
logger.Debug(i.mac + ", " + i.ip);*/
if (knownIps.ContainsKey(i.mac) && knownIps[i.mac] != i.ip)
{
logger.Info("Notifying new IP address to broker: " + i.ip);
if (rpc.NotifyIPChange() == true) // if Could not send ip addresses, try again in a while, else save it
knownIps[i.mac] = i.ip;
else
logger.Info("Could not notify ip, will retry later");
break;
}
}
}
catch (Exception e)
{
logger.Error("Error getting interfaces", e);
}
bool exit = _stopEvent.WaitOne(_delay);
if (exit)
{
logger.Debug("Exit requested on main loop");
return;
}
}
}
private void Rename(string name, string user, string oldPass, string newPass)
{
// name and newName can be different case, but still same
Info.DomainInfo info = Info.Computer.GetDomainInfo();
if ( string.Equals(info.ComputerName, name, StringComparison.CurrentCultureIgnoreCase))
{
logger.Info("Computer name is " + info.ComputerName);
rpc.SetReady();
return;
}
// Set user password if provided
if (user != null)
{
logger.Info("Setting password for user " + user);
if (Operation.ChangeUserPassword(user, oldPass, newPass) == false)
{
logger.Error("Could not change password to " + newPass + " for user " + user);
rpc.ResetManager();
return;
}
}
if (Operation.RenameComputer(name, _stopEvent, _retryDelay) == false)
{
logger.Error("Could not rename machine to \"" + name + "\"");
rpc.ResetManager();
return;
}
logger.Info("Rebooting machine");
Reboot();
}
private void OneStepJoin(string name, string domain, string ou, string account, string pass)
{
// name and newName can be different case, but still same
Info.DomainInfo info = Info.Computer.GetDomainInfo();
if (string.Equals(info.ComputerName, name, StringComparison.CurrentCultureIgnoreCase))
{
// We should be already in the domain, if not, will try second step of "multiStepJoin"
if(info.Status == Info.DomainInfo.NetJoinStatus.NetSetupDomainName ) // Already in domain
{
logger.Info("Machine " + name + " in domain " + domain);
rpc.SetReady();
return;
}
// Call multiStep, cause name is good but domain don't
MultiStepJoin(name, domain, ou, account, pass);
return;
}
// Needs to rename + join
if (Operation.RenameComputer(name, _stopEvent, _retryDelay) == false)
{
logger.Error("Could not rename machine to \"" + name + "\"");
rpc.ResetManager();
return;
}
// Now try to join domain
if (Operation.JoinDomain(domain, ou, account, pass, true, _stopEvent, _retryDelay) == false)
{
logger.Error("Could not join domain \"" + domain + "\", ou \"" + ou + "\"");
rpc.ResetManager();
return;
}
// Fine, now reboot
Reboot();
}
private void MultiStepJoin(string name, string domain, string ou, string account, string pass)
{
Info.DomainInfo info = Info.Computer.GetDomainInfo();
if (string.Equals(info.ComputerName, name, StringComparison.CurrentCultureIgnoreCase))
{
// Name already, now see if already in domain
if (info.Status == Info.DomainInfo.NetJoinStatus.NetSetupDomainName) // Already in domain
{
logger.Info("Machine " + name + " in domain " + domain);
rpc.SetReady();
return;
}
// Now try to join domain
if (Operation.JoinDomain(domain, ou, account, pass, false, _stopEvent, _retryDelay) == false)
{
logger.Error("Could not join domain \"" + domain + "\", ou \"" + ou + "\"");
rpc.ResetManager();
return;
}
}
else
{
// Try to rename machine
if (Operation.RenameComputer(name, _stopEvent, _retryDelay) == false)
{
logger.Error("Could not rename machine to \"" + name + "\"");
rpc.ResetManager();
return;
}
}
// Fine, now reboot
Reboot();
}
private void JoinDomain(string name, string domain, string ou, string account, string pass)
{
// Test to see if it is windows 7
logger.Info("Joining domain " + domain + ", under ou " + ou);
Info.OsInfo winVer = new Info.OsInfo();
if (winVer.Version == Info.OsInfo.WindowsVersion.Win7)
{
// Will do it in one step
OneStepJoin(name, domain, ou, account, pass);
}
else
{
MultiStepJoin(name, domain, ou, account, pass);
}
}
private void Reboot()
{
if (Operation.Reboot() == false)
{
logger.Error("Could not reboot machine");
rpc.ResetManager();
}
else
_reboot = true;
}
}
}

View File

@ -1,171 +0,0 @@
using System;
using System.Runtime.InteropServices;
using log4net;
namespace uds.Services
{
class ServiceInstaller
{
private static ILog logger = LogManager.GetLogger(typeof(ServiceInstaller));
#region DLLImport
[DllImport("advapi32.dll")]
public static extern IntPtr OpenSCManager(string lpMachineName, string lpSCDB, int scParameter);
[DllImport("Advapi32.dll")]
public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName,
int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName,
string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
[DllImport("advapi32.dll")]
public static extern void CloseServiceHandle(IntPtr SCHANDLE);
[DllImport("advapi32.dll")]
public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string lpServiceArgVectors);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern IntPtr OpenService(IntPtr SCHANDLE, string lpSvcName, int dwNumServiceArgs);
[DllImport("advapi32.dll")]
public static extern int DeleteService(IntPtr SVHANDLE);
[DllImport("kernel32.dll")]
public static extern int GetLastError();
#endregion DLLImport
/// <summary>
/// This method installs and runs the service in the service control manager.
/// </summary>
/// <param name="svcPath">The complete path of the service.</param>
/// <param name="svcName">Name of the service.</param>
/// <param name="svcDispName">Display name of the service.</param>
/// <returns>True if the process went thro successfully. False if there was anyerror.</returns>
public static bool InstallService(string svcPath, string svcName, string svcDispName, string description, string dependencies, bool startNow)
{
logger.Info("Installing service \"" + svcName + "\" at \"" + svcPath + "\"");
int SC_MANAGER_CREATE_SERVICE = 0x0002;
int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
//int SERVICE_DEMAND_START = 0x00000003;
int SERVICE_ERROR_NORMAL = 0x00000001;
int STANDARD_RIGHTS_REQUIRED = 0xF0000;
int SERVICE_QUERY_CONFIG = 0x0001;
int SERVICE_CHANGE_CONFIG = 0x0002;
int SERVICE_QUERY_STATUS = 0x0004;
int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
int SERVICE_START = 0x0010;
int SERVICE_STOP = 0x0020;
int SERVICE_PAUSE_CONTINUE = 0x0040;
int SERVICE_INTERROGATE = 0x0080;
int SERVICE_USER_DEFINED_CONTROL = 0x0100;
int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL);
int SERVICE_AUTO_START = 0x00000002;
try
{
IntPtr sc_handle = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (sc_handle.ToInt32() != 0)
{
IntPtr sv_handle = CreateService(sc_handle, svcName, svcDispName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, svcPath, null, 0, dependencies, null, null);
if (sv_handle.ToInt32() == 0)
{
logger.Error("Service can't be installed!!");
CloseServiceHandle(sc_handle);
return false;
}
else
{
logger.Info("Service installed");
if (startNow)
{
//now trying to start the service
int i = StartService(sv_handle, 0, null);
// If the value i is zero, then there was an error starting the service.
// note: error may arise if the service is already running or some other problem.
if (i == 0)
{
logger.Error("Can't start service!!!");
//Console.WriteLine("Couldnt start service");
return false;
}
//Console.WriteLine("Success");
}
CloseServiceHandle(sc_handle);
Microsoft.Win32.RegistryKey system, currentControlSet, services, service;
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
services = currentControlSet.OpenSubKey("Services");
service = services.OpenSubKey(svcName, true);
service.SetValue("Description", description);
return true;
}
}
else
{
logger.Error("SCM not opened successfully");
return false;
}
}
catch (Exception e)
{
throw e;
}
}
public static void StopService(string svcName, int timeoutMilliseconds = 10000)
{
logger.Debug("Stoping service " + svcName + " with timeout " + timeoutMilliseconds);
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(svcName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, timeout);
logger.Debug("Service correctly stopped");
}
catch(Exception e)
{
// ...
logger.Debug("Service could not been stoped", e);
}
}
public static bool UnInstallService(string svcName)
{
logger.Info("Uninstalling service " + svcName);
StopService(svcName);
// First, stop service
int GENERIC_WRITE = 0x40000000;
IntPtr sc_hndl = OpenSCManager(null, null, GENERIC_WRITE);
if (sc_hndl.ToInt32() != 0)
{
int DELETE = 0x10000;
IntPtr svc_hndl = OpenService(sc_hndl, svcName, DELETE);
//Console.WriteLine(svc_hndl.ToInt32());
if (svc_hndl.ToInt32() != 0)
{
int i = DeleteService(svc_hndl);
if (i != 0)
{
logger.Info("Service correctly removed");
CloseServiceHandle(sc_hndl);
return true;
}
else
{
logger.Error("Can't remove service: " + i.ToString());
CloseServiceHandle(sc_hndl);
return false;
}
}
else
return false;
}
else
{
logger.Error("SCM not opened successfully!!");
return false;
}
}
}
}

View File

@ -1,40 +0,0 @@
<?xml version="1.0"?>
<configuration>
<configSections>
<!-- Level 1 -->
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/>
<!-- Level 2 -->
</configSections>
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
<log4net>
<appender name="UDS" type="uds.RPCAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</appender>
<appender name="UDSLocal" type="log4net.Appender.FileAppender">
<file value="c:\Windows\uds.log"/>
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<!-- ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
<level value="ALL" />
<appender-ref ref="UDS"/>
<appender-ref ref="UDSLocal" />
</root>
</log4net>
</configuration>

View File

@ -1,16 +0,0 @@
 <log4net debug="true">
<appender name="UDS" type="log4net.Appender.FileAppender">
<file value="c:\Windows\uds.log"/>
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<!-- ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
<level value="DEBUG" />
<appender-ref ref="UDS" />
</root>
</log4net>

View File

@ -1,146 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{E528C884-A7FA-401F-AE2E-C1796D326461}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>uds.Services</RootNamespace>
<AssemblyName>udsService</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>
</DocumentationFile>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup>
<StartupObject>uds.Services.Application</StartupObject>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>true</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>true</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<PropertyGroup />
<PropertyGroup>
<ApplicationManifest>udsService.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\log4net\3.5\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Data" />
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup>
<Compile Include="Application.cs" />
<Compile Include="RPCAppender.cs" />
<Compile Include="Sens\EventSystemRegistrar.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Service.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ServiceInstaller.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config">
<SubType>Designer</SubType>
</None>
<None Include="logging.cfg">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<SubType>Designer</SubType>
</None>
<None Include="udsService.manifest" />
</ItemGroup>
<ItemGroup>
<COMReference Include="EventSystemLib">
<Guid>{4E14FB90-2E22-11D1-9964-00C04FBBB345}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
<COMReference Include="SensEvents">
<Guid>{D597DEED-5B9F-11D1-8DD2-00AA004ABD5E}</Guid>
<VersionMajor>2</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\rpc\tools.csproj">
<Project>{9861A89C-7007-4A42-8BEB-9914BCF5524C}</Project>
<Name>tools</Name>
</ProjectReference>
<ProjectReference Include="..\udsgui\udsgui.csproj">
<Project>{278F54DB-771A-4EF2-BEF2-9447F988303F}</Project>
<Name>udsgui</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="udsService" type="win32"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

View File

@ -1,119 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.17929
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
namespace uds.gui {
using System;
/// <summary>
/// Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc.
/// </summary>
// StronglyTypedResourceBuilder generó automáticamente esta clase
// a través de una herramienta como ResGen o Visual Studio.
// Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen
// con la opción /str o recompile su proyecto de VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Lang {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Lang() {
}
/// <summary>
/// Devuelve la instancia de ResourceManager almacenada en caché utilizada por esta clase.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("uds.gui.Lang", typeof(Lang).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Reemplaza la propiedad CurrentUICulture del subproceso actual para todas las
/// búsquedas de recursos mediante esta clase de recurso fuertemente tipado.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Busca una cadena traducida similar a You need administrator privileges to run this program..
/// </summary>
internal static string AdminNeeded {
get {
return ResourceManager.GetString("AdminNeeded", resourceCulture);
}
}
/// <summary>
/// Busca una cadena traducida similar a The parameters didn&apos;t work as expected. Check them and try again.
/// </summary>
internal static string ConnectionError {
get {
return ResourceManager.GetString("ConnectionError", resourceCulture);
}
}
/// <summary>
/// Busca una cadena traducida similar a The connection test worked..
/// </summary>
internal static string ConnectionOK {
get {
return ResourceManager.GetString("ConnectionOK", resourceCulture);
}
}
/// <summary>
/// Busca una cadena traducida similar a Connection Test Result.
/// </summary>
internal static string ConnectionTest {
get {
return ResourceManager.GetString("ConnectionTest", resourceCulture);
}
}
/// <summary>
/// Busca una cadena traducida similar a The provided parameters do not seems valid.
///The broker may be down.
///Are you sure that you want to save these parameters?.
/// </summary>
internal static string ConnetionNotAvailable {
get {
return ResourceManager.GetString("ConnetionNotAvailable", resourceCulture);
}
}
/// <summary>
/// Busca una cadena traducida similar a Error.
/// </summary>
internal static string Error {
get {
return ResourceManager.GetString("Error", resourceCulture);
}
}
}
}

View File

@ -1,135 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdminNeeded" xml:space="preserve">
<value>Sie benötigen Administratorrechte zu verkehren dieses Program.</value>
</data>
<data name="ConnectionError" xml:space="preserve">
<value>Die Parameter funktionieren nicht wie erwartet. Überprüfen Sie sie und versuchen Sie es erneut</value>
</data>
<data name="ConnectionOK" xml:space="preserve">
<value>Der Verbindungstest arbeitete.</value>
</data>
<data name="ConnectionTest" xml:space="preserve">
<value>Verbindung Testergebnis</value>
</data>
<data name="Error" xml:space="preserve">
<value>Fehler</value>
</data>
</root>

View File

@ -1,135 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdminNeeded" xml:space="preserve">
<value>Necesita ser administrador para poder ejecutar esta aplicación.</value>
</data>
<data name="ConnectionError" xml:space="preserve">
<value>Los parametros de conexión son erroneos. Reviselos y pruebe de nuevo.</value>
</data>
<data name="ConnectionOK" xml:space="preserve">
<value>El test de conexión funcionó correctamente.</value>
</data>
<data name="ConnectionTest" xml:space="preserve">
<value>Resultado del test de conexión</value>
</data>
<data name="Error" xml:space="preserve">
<value>Error</value>
</data>
</root>

View File

@ -1,135 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdminNeeded" xml:space="preserve">
<value>Vous avez besoin de privilèges d'administrateur pour exécuter ce programme.</value>
</data>
<data name="ConnectionError" xml:space="preserve">
<value>Les paramètres n'a pas fonctionné comme prévu. Les vérifier et essayez à nouveau</value>
</data>
<data name="ConnectionOK" xml:space="preserve">
<value>Le test de connexion a travaillé.</value>
</data>
<data name="ConnectionTest" xml:space="preserve">
<value>Résultat de Test de connexion</value>
</data>
<data name="Error" xml:space="preserve">
<value>Erreur</value>
</data>
</root>

View File

@ -1,140 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdminNeeded" xml:space="preserve">
<value>You need administrator privileges to run this program.</value>
</data>
<data name="ConnectionError" xml:space="preserve">
<value>The parameters didn't work as expected. Check them and try again</value>
</data>
<data name="ConnectionOK" xml:space="preserve">
<value>The connection test worked.</value>
</data>
<data name="ConnectionTest" xml:space="preserve">
<value>Connection Test Result</value>
</data>
<data name="ConnetionNotAvailable" xml:space="preserve">
<value>The provided parameters do not seems valid.
The broker may be down.
Are you sure that you want to save these parameters?</value>
</data>
<data name="Error" xml:space="preserve">
<value>Error</value>
</data>
</root>

View File

@ -1,38 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("udsgui")]
[assembly: AssemblyDescription("Gui interface for uds actor")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Virtual Cable S.L.")]
[assembly: AssemblyProduct("UDS Actor")]
[assembly: AssemblyCopyright("Copyright © Virtual Cable S.L. 2011")]
[assembly: AssemblyTrademark("UDS")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("839e8c24-f711-4eb6-8ed3-9f94e3bcba6e")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión
// mediante el asterisco ('*'), como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]

View File

@ -1,115 +0,0 @@
namespace uds.gui.forms
{
partial class Config
{
/// <summary>
/// Variable del diseñador requerida.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpiar los recursos que se estén utilizando.
/// </summary>
/// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código generado por el Diseñador de Windows Forms
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede modificar
/// el contenido del método con el editor de código.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Config));
this.label1 = new System.Windows.Forms.Label();
this.brokerAddress = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.useSecureConnection = new System.Windows.Forms.ComboBox();
this.testConnectionButton = new System.Windows.Forms.Button();
this.acceptButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// brokerAddress
//
resources.ApplyResources(this.brokerAddress, "brokerAddress");
this.brokerAddress.Name = "brokerAddress";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// useSecureConnection
//
resources.ApplyResources(this.useSecureConnection, "useSecureConnection");
this.useSecureConnection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.useSecureConnection.FormattingEnabled = true;
this.useSecureConnection.Items.AddRange(new object[] {
resources.GetString("useSecureConnection.Items"),
resources.GetString("useSecureConnection.Items1")});
this.useSecureConnection.Name = "useSecureConnection";
//
// testConnectionButton
//
resources.ApplyResources(this.testConnectionButton, "testConnectionButton");
this.testConnectionButton.Name = "testConnectionButton";
this.testConnectionButton.UseVisualStyleBackColor = true;
this.testConnectionButton.Click += new System.EventHandler(this.testConnectionButton_Click);
//
// acceptButton
//
resources.ApplyResources(this.acceptButton, "acceptButton");
this.acceptButton.Name = "acceptButton";
this.acceptButton.UseVisualStyleBackColor = true;
this.acceptButton.Click += new System.EventHandler(this.acceptButton_Click);
//
// cancelButton
//
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.Name = "cancelButton";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// Config
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.acceptButton);
this.Controls.Add(this.testConnectionButton);
this.Controls.Add(this.useSecureConnection);
this.Controls.Add(this.label2);
this.Controls.Add(this.brokerAddress);
this.Controls.Add(this.label1);
this.Name = "Config";
this.Load += new System.EventHandler(this.Config_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox brokerAddress;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox useSecureConnection;
private System.Windows.Forms.Button testConnectionButton;
private System.Windows.Forms.Button acceptButton;
private System.Windows.Forms.Button cancelButton;
}
}

View File

@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using log4net;
namespace uds.gui.forms
{
public partial class Config : Form
{
private static ILog logger = LogManager.GetLogger(typeof(config));
public Config()
{
InitializeComponent();
}
private void Config_Load(object sender, EventArgs e)
{
brokerAddress.Text = config.broker;
useSecureConnection.SelectedIndex = config.ssl ? 0 : 1;
if (Info.Computer.IsUserAdministrator() == false)
{
MessageBox.Show(Lang.AdminNeeded, Lang.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
return;
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void testConnectionButton_Click(object sender, EventArgs e)
{
rpc.Initialize(brokerAddress.Text, useSecureConnection.SelectedIndex == 0);
if (rpc.Manager.Test() == false)
{
MessageBox.Show(Lang.ConnectionError, Lang.ConnectionTest, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(Lang.ConnectionOK, Lang.ConnectionTest, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void acceptButton_Click(object sender, EventArgs e)
{
config.broker = brokerAddress.Text;
config.ssl = useSecureConnection.SelectedIndex == 0;
rpc.Initialize(config.broker, config.ssl);
if (rpc.Manager.Test() == false)
{
if (MessageBox.Show(Lang.ConnetionNotAvailable, Lang.ConnectionTest, MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
return;
}
else
logger.Info("Saved new broker configuration");
config.SaveConfig();
Close();
}
}
}

Some files were not shown because too many files have changed in this diff Show More