Call dll function from vb.net - vb.net

I have CAD dll it's called plclient_kompas.dll. This is a library for standard machinebuilding parts.
In plclient_kompas.dll contains function PLInsert3D, that puts standard part from library to 3D assembly.
In manual to this library said that:
HRESULT **PLInsert3D**(
[in] IPARTLibProvider* aPLClient;
[in] IBOResponseDisp* aMethodResponse;
[in] ksPlacement* aPlacement;
[out, retval] IDispatch** result);
So I want to call this function from vs2017 vb.net code like this:
<DllImport("C:\Program Files\ASCON\KOMPAS-3D v17\Libs\PARTLib\Clients\plclient_kompas.dll", CallingConvention:=CallingConvention.StdCall)>
Public Shared Function **PLInsert3D**(aPLClient As IPARTLibProvider, aMethodResponse As BOResponse, aPlacement As ksPlacement) As ksPart
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
iMainPart = **PLInsert3D**(aPLClient, aMethodResponse, aPlacement)
End Sub
But in this line:
iMainPart = **PLInsert3D**(aPLClient, aMethodResponse, aPlacement)
I have error access violation exception.
What I do wrong? Any help will be appreciated. Thanks!
Addition what I wrote.
This is my code in vb.net:
Imports Kompas6API5
Imports KompasAPI7
Imports PARTLibClient
Imports BOSimple
Imports Kompas6Constants3D
Imports System.Runtime.InteropServices
Imports stdole
Public Class Form1
<DllImport("C:\Program Files\ASCON\KOMPAS-3D v17\Libs\PARTLib\Clients\plclient_kompas.dll", CallingConvention:=CallingConvention.StdCall)>
Public Shared Function PLInsert3D(ByRef aPLClient As IPARTLibProvider, ByRef aMethodResponse As BOResponse, ByRef aPlacement As ksPlacement) As <MarshalAs(UnmanagedType.Interface)> ksPart
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim kompas As Object
Dim ksdoc As Object
kompas = New Kompas6API5.Application
kompas.Visible = True
ksdoc = kompas.Document3D
ksdoc.Create(False, False)
ksdoc.Filename = "C:\Users\Baha1990\Documents\Visual Studio 2017\Projects\Kompas3D\3d files\1.a3d"
ksdoc.UpdateDocumentParam
ksdoc.Save
Dim aPLClient As BOSimpleProvider
aPLClient = New PARTLibClient.BOSimpleProvider
Dim Location As String
Dim Response As Object
Location = ""
Response = aPLClient.SelectEx(0, 0, Location, 0)
Dim aMethodResponse As BOResponse
aMethodResponse = aPLClient.GetMethod(Location, "КОМПАС 3D")
Dim iDoc3D As ksDocument3D
Dim iMainPart As ksPart
Dim aPlacement As ksPlacement
iDoc3D = kompas.ActiveDocument3D
iMainPart = iDoc3D.GetPart(-1)
aPlacement = iMainPart.GetPlacement
aPlacement.SetOrigin(0, 0, 0)
iMainPart = PLInsert3D(aPLClient, aMethodResponse, aPlacement)
End Sub
This is a sample from API manual in C#:
// Тестовая библиотека вставки объекта в КОМПАС из СИ
/*
* Необходимо у подключаемых библиотек BOSimple и PARTLibClient выставить значение параметра
* Embed Interop Types = False
*
* */
using System;
using Microsoft.Win32;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using KAPITypes;
using Kompas6Constants;
using Kompas6API5;
using Kompas6API7;
using PARTLibClient;
using BOSimple;
using Kompas6Constants3D;
using stdole;
using System.Runtime.Versioning;
namespace PartLibAPI
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class InsertKompas
{
const string _LIBRARYNAME = "Вставка изделия в Компас из СИ";
const string _KEYNAME = #"SOFTWARE\Classes\CLSID\{";
const string _KOMPASLIBRARY = "Kompas_Library";
const string _DLLPATH = "plclient_kompas.dll";
const string _KERNEL32 = "kernel32.dll";
#region Методы для работы библиотеки в Компас
private KompasObject _kompas;
// Название библиотеки
[return: MarshalAs(UnmanagedType.BStr)]
public string GetLibraryName()
{
return _LIBRARYNAME;
}
// Головная функция библиотеки
public void ExternalRunCommand([In] short command, [In] short mode, [In, MarshalAs(UnmanagedType.IDispatch)] object kompas_)
{
_kompas = (KompasObject)kompas_;
switch (command)
{
case 1:
InsertInKompas(_kompas);
break;
}
}
// Функция получения меню
// Описание функции можно найти в SDK API Компас
[return: MarshalAs(UnmanagedType.BStr)]
public string ExternalMenuItem(short number, ref short itemType, ref short command)
{
var result = string.Empty;
itemType = 1; // "MENUITEM"
switch (number)
{
case 1:
result = "Вставить";
command = 1;
break;
//
// Для корректной работы библиотеки необходимо добавить конец меню (или подменю)
//
case 2:
command = -1;
itemType = 3; // "ENDMENU"
break;
}
return result;
}
#endregion
// Делегаты для работы с методами из plclient_kompas.dll
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int _PLInsert2D(IPARTLibProvider aPLClient, IBOResponse aMethodResponse, double aX, double aY, double aAngle);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void _PLInsert3D([Out] out IDispatch retVal, IPARTLibProvider aPLClient, IBOResponse aMethodResponse, ksPlacement aPlacement);
private void InsertInKompas(KompasObject kompas)
{
// Подключаемся к plclient_kompas.dll (получаем ссылку на запущенный экземпляр в процессе Компаса)
IntPtr pDll = IntPtr.Zero;
try
{
pDll = LoadLibrary(_DLLPATH);
if (pDll == IntPtr.Zero)
throw new Exception("Не могу найти plclient_kompas.dll");
// Получаем адреса экспортируемых функций из ранее загруженной plclient_kompas.dll
var pProc2D = GetProcAddress(pDll, "PLInsert2D");
var pProc3D = GetProcAddress(pDll, "PLInsert3D");
// Получаем экземпляры делегатов, приведенных к соответствующему типу
var PLInsert2D = (_PLInsert2D)Marshal.GetDelegateForFunctionPointer(pProc2D, typeof(_PLInsert2D));
var PLInsert3D = (_PLInsert3D)Marshal.GetDelegateForFunctionPointer(pProc3D, typeof(_PLInsert3D));
IApplication kompasApp = kompas.ksGetApplication7();
if (kompasApp == null)
throw new Exception("Не удалось получить указатель на интерфейс приложения!");
var doc2D = (Document2D)kompas.ActiveDocument2D();
var doc3D = (Document3D)kompas.ActiveDocument3D();
if ((doc2D == null) && (doc3D == null))
throw new Exception("Откройте документ или создайте новый!");
// Подключаемся к API справочника
IPARTLibProvider PLClient = null;
try
{
PLClient = new BOSimpleProvider();
var errorMsg = String.Empty;
// Подключаемся к серверу приложений
if (PLClient.Connect(ref errorMsg) == 0)
{
try
{
// Получаем доступ к изделиям и папкам в справочнике
var commonData = PLClient.CreateCommonDataObj();
commonData.InitUserData();
string plm2D = "2D"; // Документ 2D
string plm3D = "Solid3D"; // Документ 3D
// Типы документов Компаса
string[] methodNames = { "", "КОМПАС 2D", "КОМПАС 2D", "КОМПАС 3D", "КОМПАС 3D", "КОМПАС 3D", "" };
string[] docName = { "?", plm2D, plm2D, plm3D, plm3D, plm3D, "?" };
// Получаем тип документа
var docType = GetDocType(kompasApp);
ksPart mainPart = null;
ksPart pPart = null;
ksPlacement partPlace = null;
if (docType == DocumentTypeEnum.ksDocumentAssembly)
{
if (doc3D != null)
{
mainPart = doc3D.GetPart((short)Part_Type.pTop_Part);
if (mainPart != null)
{
pPart = doc3D.GetPart(0);
partPlace = pPart != null ? pPart.GetPlacement() : mainPart.GetPlacement();
}
}
}
// Задаем режим работы справочника в зависимости от типа активного документа в КОМПАС
commonData.SetFindOptions(docName[(int)docType]);
// Путь до корневого каталога с ISO стандартами по уникальному ID
var ISOFolder = commonData.FolderByID("A259_151417DFF6474BF6");
// Просматриваем каталог в глубину
while (ISOFolder.FolderCollection().Count() > 0)
{
ISOFolder = ISOFolder.FolderCollection().Folder(0);
// В случае если в каталоге есть хотя бы один класс
if (ISOFolder.ClassCollection().Count() > 0)
{
// Получаем указатель на интерфейс первой типоразмерной таблицы его изделий
var ISOClass = ISOFolder.ClassCollection().plClass(0);
var instance = ISOClass.Instances("", docName[(int)docType]);
var paramGrid = instance.ParamGrid(0);
// Просматриваем типоразмерную таблицу сверху-вниз
for (int i = 0; i < paramGrid.PGRowCount(); i++)
{
// Выбираем строку
paramGrid.SelectRow(i);
// Получаем полный location получившегося изделия
var location = instance.plPart().GetLocation(0);
// Получаем метод для вставки изделия в зависимости от типа активного документа
var methodResponce = PLClient.GetMethod(location, methodNames[(int)docType]);
// Вставляем изделие в КОМПАС
var X = 5 * i * Math.Sin(15 * Math.PI * i / 180);
var Y = 5 * i * Math.Cos(15 * Math.PI * i / 180);
var Angle = 180 - i * 15;
IDispatch kPart;
switch (docType)
{
case DocumentTypeEnum.ksDocumentAssembly:
// Задаем место в сборке
partPlace.SetOrigin(X, Y, 0);
PLInsert3D(out kPart, PLClient, methodResponce, partPlace);
break;
case DocumentTypeEnum.ksDocumentDrawing:
PLInsert2D(PLClient, methodResponce, X, Y, Angle);
break;
case DocumentTypeEnum.ksDocumentFragment:
PLInsert2D(PLClient, methodResponce, X, Y, Angle);
break;
case DocumentTypeEnum.ksDocumentSpecification:
PLInsert3D(out kPart, PLClient, methodResponce, null);
break;
}
}
}
}
}
catch (Exception ex)
{
kompas.ksMessage(ex.Message);
}
finally
{
// Отключаемся от сервера приложений
PLClient.Disconnect();
}
}
else
kompas.ksMessage("Ошибка подключения к серверу приложений: " + errorMsg);
}
catch (Exception ex)
{
kompas.ksMessage("Ошибка! Не удалось создать COM-объект." + ex.Message);
}
}
catch (Exception ex)
{
kompas.ksMessage(ex.Message);
}
finally
{
// Освобождаем загруженную plclient_kompas.dll
FreeLibrary(pDll);
}
}
/// <summary>
/// Метод определения типа документа
/// </summary>
/// <param name="kompasApp"></param>
/// <returns></returns>
private DocumentTypeEnum GetDocType(IApplication kompasApp)
{
return kompasApp.ActiveDocument == null ? DocumentTypeEnum.ksDocumentUnknown : kompasApp.ActiveDocument.DocumentType;
}
// Импортируем в проект методы из kernel32.dll для подключения к plclient_kompas.dll
[DllImport(_KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr LoadLibrary(string libFilename);
[DllImport(_KERNEL32, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
static internal extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName/*lpcstr*/);
[DllImport(_KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.Process)]
public static extern bool FreeLibrary(IntPtr hModule);
#region COM Registration
// Эта функция выполняется при регистрации класса для COM
// Она добавляет в ветку реестра компонента раздел Kompas_Library,
// который сигнализирует о том, что класс является приложением Компас,
// а также заменяет имя InprocServer32 на полное, с указанием пути.
// Все это делается для того, чтобы иметь возможность подключить
// библиотеку на вкладке ActiveX.
[ComRegisterFunction]
public static void RegisterKompasLib(Type t)
{
RegistryKey regKey = Registry.LocalMachine;
try
{
var keyName = string.Format("{0}{1}{2}", _KEYNAME, t.GUID.ToString(), "}");
regKey = regKey.OpenSubKey(keyName, true);
regKey.CreateSubKey(_KOMPASLIBRARY);
regKey = regKey.OpenSubKey("InprocServer32", true);
regKey.SetValue(null, System.Environment.GetFolderPath(Environment.SpecialFolder.System) + #"\mscoree.dll");
}
catch (Exception ex)
{
MessageBox.Show(string.Format("При регистрации класса для COM-Interop произошла ошибка:\n{0}", ex));
}
finally
{
regKey.Close();
}
}
// Эта функция удаляет раздел Kompas_Library из реестра
[ComUnregisterFunction]
public static void UnregisterKompasLib(Type t)
{
RegistryKey regKey = Registry.LocalMachine;
var keyName = string.Format("{0}{1}{2}", _KEYNAME, t.GUID.ToString(), "}");
RegistryKey subKey = regKey.OpenSubKey(keyName, true);
try
{
subKey.DeleteSubKey(_KOMPASLIBRARY);
}
finally { subKey.Close(); }
}
#endregion
}
}

Related

Query with distinct keyword and subquery not working in Hive with udf

Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
public class Lookup extends GenericUDF {
private static String delimiter = "|";
private ConcurrentHashMap < String, HashMap < String, String >> fileMap = new ConcurrentHashMap < String, HashMap < String, String >> ();
protected String loggedInUser;
protected String loggedInApplication;
private transient GenericUDFUtils.StringHelper returnHelper;
private transient StringConverter[] stringConverter;
private static final Logger LOG = LoggerFactory.getLogger(Lookup.class.getName());
#Override
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
if (arguments.length < 2) {
throw new UDFArgumentLengthException(
"lookup takes 2 or more arguments");
}
stringConverter = new StringConverter[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (arguments[0].getCategory() != Category.PRIMITIVE) {
throw new UDFArgumentException(
"lookup only takes primitive types");
}
stringConverter[i] = new PrimitiveObjectInspectorConverter.StringConverter(
(PrimitiveObjectInspector) arguments[i]);
}
setLoggedInUser();
returnHelper = new GenericUDFUtils.StringHelper(
PrimitiveCategory.STRING);
LOG.info("initialize successful");
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
}
private void setLoggedInUser() {
if (loggedInUser == null) {
loggedInUser = SessionState.get().getUserName();
if (loggedInUser != null) {
int idx = loggedInUser.indexOf('.');
loggedInApplication = idx > -1 ? loggedInUser.substring(0, idx) : null;
}
}
}
private void initMap(String f) {
LOG.info("initMap involked");
if (loggedInApplication == null)
throw new NullPointerException(
"Unable to retrieve application name from user.");
String filePath = "/basepath/" + loggedInApplication.toLowerCase() + "/" + f +
".txt";
String line = null;
try {
LOG.info("filePath =" + filePath);
FileSystem fs = FileSystem.get(new Configuration());
FSDataInputStream in = fs.open(new Path(filePath));
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
HashMap < String, String > map = new HashMap < String, String > ();
while ((line = br.readLine()) != null) {
// ignore comment lines
if (line.startsWith("#")) {
continue;
}
String[] strs = line.split("\t");
if (strs.length == 2) {
map.put(strs[0].toUpperCase().trim(), strs[1].trim());
} else if (strs.length > 2) {
map.put(getKey(strs), strs[strs.length - 1].trim());
}
}
fileMap.put(f, map);
br.close();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public Text getValue(String s, String f) {
initMap(f);
HashMap < String, String > map = fileMap.get(f);
LOG.info("getValue() fileMap =" + fileMap);
String v = map.get(s);
return v == null ? null : new Text(v);
}
#Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
String val = buildVal(arguments);
String lookupFile = (String) stringConverter[arguments.length - 1].convert(arguments[arguments.length - 1].get());
Text returnVal = getValue(val.toUpperCase(), lookupFile.toLowerCase());
return returnVal == null ? null : returnHelper.setReturnValue(returnVal.toString());
}
#Override
public String getDisplayString(String[] arg0) {
return "lookup()";
}
private String buildVal(DeferredObject[] arguments) throws HiveException {
StringBuilder builder = new StringBuilder();
int cnt = arguments.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append((String) stringConverter[i].convert(arguments[i].get()));
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
private String getKey(String[] strs) {
StringBuilder builder = new StringBuilder();
int cnt = strs.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append(strs[i].toUpperCase().trim());
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
}

error is occuring while creating custom tokenizer in lucene 7.3

I m trying to create new tokenizer by refering book tamingtext (which uses lucene 3.+ api) using new lucene api 7.3, but it is giving me error as mentioned below
java.lang.IllegalStateException: TokenStream contract violation: reset()/close() call missing, reset() called multiple times, or subclass does not call super.reset(). Please see Javadocs of TokenStream class for more information about the correct consuming workflow.
at org.apache.lucene.analysis.Tokenizer$1.read(Tokenizer.java:109)
at java.io.Reader.read(Reader.java:140)
at solr.SentenceTokenizer.fillSentences(SentenceTokenizer.java:43)
at solr.SentenceTokenizer.incrementToken(SentenceTokenizer.java:55)
at solr.NameFilter.fillSpans(NameFilter.java:56)
at solr.NameFilter.incrementToken(NameFilter.java:88)
at spec.solr.NameFilterTest.testNameFilter(NameFilterTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Here is my SentenceTokenizer class
Initializing method, in older api there was super(Reader); but in current api there is no access to Reader class
public SentenceTokenizer(SentenceDetector detector) {
super();
setReader(reader);
this.sentenceDetector = detector;
}
Here is my reset method
#Override
public void reset() throws IOException {
super.reset();
sentenceDetector = null;
}
When i tried to access this method from custom TokenFilter, I m getting above error
public void fillSentences() throws IOException {
char[] c = new char[256];
int size = 0;
StringBuilder stringBuilder = new StringBuilder();
while ((size = input.read(c)) >= 0) {
stringBuilder.append(c, 0, size);
}
String temp = stringBuilder.toString();
inputSentence = temp.toCharArray();
sentenceSpans = sentenceDetector.sentPosDetect(temp);
tokenOffset = 0;
}
#Override
public final boolean incrementToken() throws IOException {
if (sentenceSpans == null) {
//invoking following method
fillSentences();
}
if (tokenOffset == sentenceSpans.length) {
return false;
}
Span sentenceSpan = sentenceSpans[tokenOffset];
clearAttributes();
int start = sentenceSpan.getStart();
int end = sentenceSpan.getEnd();
charTermAttribute.copyBuffer(inputSentence, start, end - start);
positionIncrementAttribute.setPositionIncrement(1);
offsetAttribute.setOffset(start, end);
tokenOffset++;
return true;
}
Here is my custom TokenFilter class
public final class NameFilter extends TokenFilter {
public static final String NE_PREFIX = "NE_";
private final Tokenizer tokenizer;
private final String[] tokenTypeNames;
private final NameFinderME[] nameFinderME;
private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class);
private final PositionIncrementAttribute positionIncrementAttribute = addAttribute(PositionIncrementAttribute.class);
private final CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private String text;
private int baseOffset;
private Span[] spans;
private String[] tokens;
private Span[][] foundNames;
private boolean[][] tokenTypes;
private int spanOffsets = 0;
private final Queue<AttributeSource.State> tokenQueue =
new LinkedList<>();
public NameFilter(TokenStream in, String[] modelNames, NameFinderME[] nameFinderME) {
super(in);
this.tokenizer = SimpleTokenizer.INSTANCE;
this.nameFinderME = nameFinderME;
this.tokenTypeNames = new String[modelNames.length];
for (int i = 0; i < modelNames.length; i++) {
this.tokenTypeNames[i] = NE_PREFIX + modelNames[i];
}
}
//consumes tokens from the upstream tokenizer and buffer them in a
//StringBuilder whose contents will be passed to opennlp
protected boolean fillSpans() throws IOException {
if (!this.input.incrementToken()) return false;
//process the next sentence from the upstream tokenizer
this.text = input.getAttribute(CharTermAttribute.class).toString();
this.baseOffset = this.input.getAttribute(OffsetAttribute.class).startOffset();
this.spans = this.tokenizer.tokenizePos(text);
this.tokens = Span.spansToStrings(spans, text);
this.foundNames = new Span[this.nameFinderME.length][];
for (int i = 0; i < nameFinderME.length; i++) {
this.foundNames[i] = nameFinderME[i].find(tokens);
}
//insize
this.tokenTypes = new boolean[this.tokens.length][this.nameFinderME.length];
for (int i = 0; i < nameFinderME.length; i++) {
Span[] spans = foundNames[i];
for (int j = 0; j < spans.length; j++) {
int start = spans[j].getStart();
int end = spans[j].getEnd();
for (int k = start; k < end; k++) {
this.tokenTypes[k][i] = true;
}
}
}
spanOffsets = 0;
return true;
}
#Override
public boolean incrementToken() throws IOException {
//if there's nothing in the queue
if(tokenQueue.peek()==null){
//no span or spans consumed
if (spans==null||spanOffsets>=spans.length){
if (!fillSpans())return false;
}
if (spanOffsets>=spans.length)return false;
//copy the token and any types
clearAttributes();
keywordAttribute.setKeyword(false);
positionIncrementAttribute.setPositionIncrement(1);
int startOffset = baseOffset +spans[spanOffsets].getStart();
int endOffset = baseOffset+spans[spanOffsets].getEnd();
offsetAttribute.setOffset(startOffset,endOffset);
charTermAttribute.setEmpty()
.append(tokens[spanOffsets]);
//determine of the current token is of a named entity type, if so
//push the current state into the queue and add a token reflecting
// any matching entity types.
boolean [] types = tokenTypes[spanOffsets];
for (int i = 0; i < nameFinderME.length; i++) {
if (types[i]){
keywordAttribute.setKeyword(true);
positionIncrementAttribute.setPositionIncrement(0);
tokenQueue.add(captureState());
positionIncrementAttribute.setPositionIncrement(1);
charTermAttribute.setEmpty().append(tokenTypeNames[i]);
}
}
}
spanOffsets++;
return true;
}
#Override
public void close() throws IOException {
super.close();
reset();
}
#Override
public void reset() throws IOException {
super.reset();
this.spanOffsets = 0;
this.spans = null;
}
#Override
public void end() throws IOException {
super.end();
reset();
}
}
here is my test case for following class
#Test
public void testNameFilter() throws IOException {
Reader in = new StringReader(input);
Tokenizer tokenizer = new SentenceTokenizer( detector);
tokenizer.reset();
NameFilter nameFilter = new NameFilter(tokenizer, modelName, nameFinderMES);
nameFilter.reset();
CharTermAttribute charTermAttribute;
PositionIncrementAttribute positionIncrementAttribute;
OffsetAttribute offsetAttribute;
int pass = 0;
while (pass < 2) {
int pos = 0;
int lastStart = 0;
int lastEnd = 0;
//error occur on below invoke
while (nameFilter.incrementToken()) {
}
}
I have added following changes in my code and it work fine but i m now sure it is correct answer
public SentenceTokenizer(Reader reader,SentenceDetector sentenceDetector) {
super();
this.input =reader;
this.sentenceDetector = sentenceDetector;
}

Bukkit NullPointerException onEnable()

I've been working on a new plugin, and when I load it up, it gives me a "NullPointerException" error, and I can't seem to find where it could find an error. Here is the error:
[20:15:45] [Server thread/INFO]: [EntityManager] Enabling EntityManager v3.0.0.4
[20:15:45] [Server thread/INFO]: [0;31;1mEntityManager [0;32;1m3.0.0.4[0;36;1m Enabled![m
[20:15:45] [Server thread/ERROR]: Error occurred while enabling EntityManager v3.0.0.4 (Is it up to date?)
java.lang.NullPointerException
at me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296) ~[?:?]
at me.AngryCupcake274.EntityManager.EntityManager.onEnable(EntityManager.java:63) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:316) ~[spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:332) [spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:417) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.loadPlugin(CraftServer.java:476) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.enablePlugins(CraftServer.java:394) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.n(MinecraftServer.java:360) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.g(MinecraftServer.java:334) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.a(MinecraftServer.java:290) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.DedicatedServer.init(DedicatedServer.java:210) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.run(MinecraftServer.java:458) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.ThreadServerApplication.run(SourceFile:628) [spigot.jar:git-Spigot-1649]
package me.AngryCupcake274.EntityManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.*;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
public class EntityManager extends JavaPlugin implements Listener {
RemoveEntities reme;
CommandHandler comh;
CleanEntities cent;
int loopdelay;
String oneminutemessage;
String oneminutecolor;
String threesecondsmessage;
String threesecondscolor;
String twosecondsmessage;
String twosecondscolor;
String onesecondmessage;
String onesecondcolor;
String finalmessage;
String finalcolor;
String oneMinWarn;
String threeSecWarn;
String twoSecWarn;
String oneSecWarn;
String removeInfo;
String[] worldNames;
Server server = Bukkit.getServer();
ConsoleCommandSender console = server.getConsoleSender();
PluginDescriptionFile pdf = this.getDescription();
String pdfEnable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.AQUA + " Enabled!";
String pdfDisable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.DARK_PURPLE + " Enabled!";
Player cleaner;
int counter = 0;
int totalcounter = 0;
#Override
public void onEnable() {
console.sendMessage(pdfEnable);
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
saveDefaultConfig();
loadConfiguration();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
for (int first = 0; first >= 1; first++) {
cleanUp();
}
}
}, 0L, 12000L);
}
#Override
public void onDisable() {
console.sendMessage(pdfDisable);
}
#SuppressWarnings("deprecation")
public void cleanUp() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneMinWarn);
}
console.sendMessage(oneMinWarn);
BukkitScheduler warn3 = Bukkit.getServer().getScheduler();
warn3.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
}
}, 1220L);
BukkitScheduler warn2 = Bukkit.getServer().getScheduler();
warn2.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 1240L);
BukkitScheduler warn1 = Bukkit.getServer().getScheduler();
warn1.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 1260L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 1280L);
}
#SuppressWarnings("deprecation")
public void cleanUpCommand() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
BukkitScheduler warn2c = Bukkit.getServer().getScheduler();
warn2c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 20L);
BukkitScheduler warn1c = Bukkit.getServer().getScheduler();
warn1c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 40L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(removeInfo);
}
console.sendMessage(removeInfo);
}
}, 60L);
}
public void cleanUpCommand2() {
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 0L);
}
public void loadConfiguration() {
String ltime = "looptime";
String onemmsg = "oneminute.message";
String onemcolor = "oneminute.color";
String threesmsg = "threeseconds.message";
String threescolor = "threeseconds.color";
String twosmsg = "twoseconds.message";
String twoscolor = "twoseconds.color";
String onesmsg = "onesecond.message";
String onescolor = "onesecond.color";
String fmsg = "final.message";
String fcolor = "final.color";
String arrowr = "arrow";
String boatr = "boat";
String itemr = "dropped_item";
String eggr = "egg";
String enderdragonr = "ender_dragon";
String enderpearlr = "ender_pearl";
String endersignalr = "ender_signal";
String xporbr = "experience_orb";
String fireballr = "fireball";
String fireworkr = "firework";
String fishinghookr = "fishing_hook";
String itemframer = "item_frame";
String leashr = "leash_hitch";
String lightningr = "lightning";
String minecartr = "minecart";
String minecartchestr = "minecart_chest";
String minecartcommandr = "minecart_command";
String minecartfurnacer = "minecart_furnace";
String minecarthopperr = "minecart_hopper";
String minecartmobspawnerr = "minecart_mob_spawner";
String minecarttntr = "minecart_tnt";
String paintingr = "painting";
String primedtntr = "primed_tnt";
String sfireballr = "small_fireball";
String snowballr = "snowball";
String splashpotionr = "splash_potion";
String expbottler = "exp_bottle";
String thrownxpbottler = "thrown_exp_bottle";
String witherskullr = "wither_skull";
getConfig().addDefault(ltime, (10 * 60 * 20));
getConfig().addDefault(onemmsg,
"Ground items will be removed in 1 minute!");
getConfig().addDefault(onemcolor, "AQUA");
getConfig().addDefault(threesmsg,
"Ground items will be removed in 3 seconds!");
getConfig().addDefault(threescolor, "DARK_GREEN");
getConfig().addDefault(twosmsg, "2 seconds!");
getConfig().addDefault(twoscolor, "GOLD");
getConfig().addDefault(onesmsg, "1 second!");
getConfig().addDefault(onescolor, "RED");
getConfig().addDefault(fmsg, "Ground items will be removed!");
getConfig().addDefault(fcolor, "DARK_RED");
getConfig().addDefault(arrowr, true);
getConfig().addDefault(boatr, false);
getConfig().addDefault(itemr, true);
getConfig().addDefault(eggr, true);
getConfig().addDefault(enderdragonr, false);
getConfig().addDefault(enderpearlr, true);
getConfig().addDefault(endersignalr, true);
getConfig().addDefault(xporbr, true);
getConfig().addDefault(fireballr, true);
getConfig().addDefault(fireworkr, true);
getConfig().addDefault(fishinghookr, false);
getConfig().addDefault(itemframer, false);
getConfig().addDefault(leashr, false);
getConfig().addDefault(lightningr, true);
getConfig().addDefault(minecartr, false);
getConfig().addDefault(minecartchestr, false);
getConfig().addDefault(minecartcommandr, false);
getConfig().addDefault(minecartfurnacer, false);
getConfig().addDefault(minecarthopperr, false);
getConfig().addDefault(minecartmobspawnerr, false);
getConfig().addDefault(minecarttntr, false);
getConfig().addDefault(paintingr, false);
getConfig().addDefault(primedtntr, true);
getConfig().addDefault(sfireballr, true);
getConfig().addDefault(snowballr, true);
getConfig().addDefault(splashpotionr, true);
getConfig().addDefault(expbottler, true);
getConfig().addDefault(thrownxpbottler, true);
getConfig().addDefault(witherskullr, true);
getConfig().options().copyDefaults(true);
saveConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
oneMinWarn = ChatColor.valueOf(oneminutecolor) + oneminutemessage;
threeSecWarn = ChatColor.valueOf(threesecondscolor)
+ threesecondsmessage;
twoSecWarn = ChatColor.valueOf(twosecondscolor) + twosecondsmessage;
oneSecWarn = ChatColor.valueOf(onesecondcolor) + onesecondmessage;
removeInfo = ChatColor.valueOf(finalcolor) + finalmessage;
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
saveDefaultConfig();
}
public void reloadPlugin() {
reloadConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
getServer().getScheduler().cancelTasks(this);
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
}
}
me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296)
The exception is thrown at line 296 of your EntityManager.java file.
reme.arrow = getConfig().getBoolean("arrow");
At this point of time reme is still null and therefore you can't assign arrow.
You should ensure that RemoveEntitites is already instantiated once you call loadConfiguration() in your onEnable() method.
Also see What is a NPE and how do I fix it?.
I did it!
Instead of setting the RemoveEntities variables, I told the RemoveEntities class to find the variables in the EntityManager class.

Rewriting from MonoTouch Application to MonoDroid

I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.

Silverlight-DLL communication issue

Problems with Silverlight 4 application.
In this application every client session creates a separate process, which calls a DLL.
Communication with DLL is built as in the following callstack (for two functions: one working, another - not).
There are 2 functions in DLL (both work fine):
extern "C" BOOL __stdcall DocRunExternPageDividions(const char *docId, int num_form, int PageNum, int *Vcols, int **Vvalues, int *Hcols, int **Hvalues)
{
LOG_START_FUNCTION
BOOL res = 1;
__try {
res = DocRunExternPageDividions1(docId, num_form, PageNum, Vcols, Vvalues, Hcols, Hvalues);
}
__except(ExFilter(GetExceptionInformation()))
{
AfxThrowUserException();
}
LOG_STOP_FUNCTION
return res;
}
extern "C" BOOL __stdcall DocRunExternPageBreakRects(const char *docId, int num_form, int PageNum)
{
LOG_START_FUNCTION
BOOL res = 1;
__try {
res = DocRunExternPageBreakRects1(docId, num_form, PageNum);
}
__except(ExFilter(GetExceptionInformation()))
{
AfxThrowUserException();
}
LOG_STOP_FUNCTION
return res;
}
To call this functions server has two delegates:
private delegate void DocRunExternPageBreakRectsDelegate(string docId, int DocNum, int PageNum);
private delegate void DocRunExternPageDividionsDelegate(
string docId, int DocNum, int PageNum, out int Vcols, out IntPtr VoutArray, out int Hcols,
out IntPtr HoutArray);
... two delegate instances and corresponding functions:
private DocRunExternPageBreakRectsDelegate DocRunExternPageBreakRectsD;
DocRunExternPageBreakRectsD =
Marshal.GetDelegateForFunctionPointer(ptrDocRunExternPageBreakRects,
typeof (DocRunExternPageBreakRectsDelegate)) as
DocRunExternPageBreakRectsDelegate;
private DocRunExternPageDividionsDelegate DocRunExternPageDividionsD;
DocRunExternPageDividionsD =
Marshal.GetDelegateForFunctionPointer(ptrDocRunExternPageDividionsD,
typeof (DocRunExternPageDividionsDelegate)) as
DocRunExternPageDividionsDelegate;
public void DocRunExternPageDividions(string docId, int DocNum, int PageNum, out int[] vert, out int[] horz) {
IntPtr VoutArray, HoutArray;
int vcols, hcols;
DocRunExternPageDividionsD(docId, DocNum, PageNum, out vcols, out VoutArray, out hcols, out HoutArray);
marshal(VoutArray, out vert, vcols);
marshal(HoutArray, out horz, hcols);
}
public void DocRunExternPageBreakRects(string docId, int DocNum, int PageNum) {
DocRunExternPageBreakRectsD(docId, DocNum, PageNum);
}
Each of these functions is called here (server code):
public bool PageBreakRects(string docId, int DocNum, int PageNum, out int[] vert, out int[] horz) {
bool result;
vert = null;
horz = null;
Program.WriteUserMessage("Called PageBreakRects(" + docId + ", " + DocNum + ", " + PageNum + ")");
try {
DocRunExternPageBreakRects(docId, DocNum, PageNum);
DocRunExternPageDividions(docId, 0, PageNum, out vert, out horz);
result = true;
} catch (Exception ex) {}
return result;
}
public bool GetPageDividions(string docID, int Id, int pageNumber, out int[] vert, out int[] horz) {
bool result = false;
vert = null;
horz = null;
try {
DocRunExternPageDividions(docID, Id, pageNumber, out vert, out horz);
result = true;
} catch (Exception) {}
return result;
}
Each of them - are called here:
public DocDividionsResult PageBreakRects(string docID, int DocNum, int pageNumber) {
var result = new DocDividionsResult();
int[] vert;
int[] horz;
result.Data = new List<object> { Program.DllWrapper.PageBreakRects(docID, DocNum, pageNumber, out vert, out horz) };
result.Vert = vert;
result.Horz = horz;
return result;
}
public DocDividionsResult GetPageDividions(string docID, int formId, int pageNumber) {
var result = new DocDividionsResult();
int[] vert;
int[] horz;
result.Data = new List<object>
{Program.DllWrapper.GetPageDividions(docID, formId, pageNumber, out vert, out horz)};
result.Vert = vert;
result.Horz = horz;
return result;
}
Then - within lambda-expressions:
public bool GetPageDividions(string docID, int formId, int pageNumber, out int[] vert, out int[] horz) {
bool result = false;
int []localVert = null;
int []localHorz = null;
if (_wp != null) {
if (Service<IWPCommunication>.Use(TestService =>
{
TestService.Test(UserId);
},
WPService =>
{
DocDividionsResult br = WPService.GetPageDividions(docID, formId, pageNumber);
if (br != null && br.Data != null && br.Data.Length == 1)
{
result = (bool)br.Data[0];
localVert = br.Vert;
localHorz = br.Horz;
}
}, Id, FS) == 0)
{
...
result = false;
}
}
vert = localVert;
horz = localHorz;
return result;
}
public bool PageBreakRects(string docId, int DocNum, int PageNum) {
bool result = false;
if (_wp != null)
{
if (Service<IWPCommunication>.Use(TestService =>
{
TestService.Test(UserId);
},
WPService =>
{
DocDividionsResult br = WPService.PageBreakRects(docId, DocNum, PageNum);
if (br != null && br.Data != null && br.Data.Length == 1) {
result = (bool)br.Data[0];
}
}, Id, FS) == 0)
{
...
result = false;
}
}
return result;
}
The "Use" function (used above):
public static int Use(UseServiceDelegate<T> codeTest, UseServiceDelegate<T> codeBlock, string SessionId, FileStream fs, bool throwException) {
IClientChannel texy = (IClientChannel)_testFactory.CreateChannel(new EndpointAddress("net.pipe://localhost/X2WPServiceUID" + SessionId));
IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel(new EndpointAddress("net.pipe://localhost/X2WPServiceUID" + SessionId));
int returnCode = 0;
try {
if (codeTest != null) {
codeTest((T)texy);
texy.Close();
}
returnCode = 1;
if (codeBlock != null) {
codeBlock((T)proxy);
proxy.Close();
}
returnCode = 2;
} catch(Exception e) {
if (returnCode == 1 && throwException)
throw e;
} finally {
if (returnCode == 0 && codeTest != null)
texy.Abort();
else if (returnCode == 1 && codeBlock != null)
proxy.Abort();
}
return returnCode;
}
Client communication is omitted as exception is raised on the server side.
GetPageDividions function works fine, bug PageBreakRects - not: the line
DocDividionsResult br = WPService.PageBreakRects(docId, DocNum, PageNum);
throws the following exception:
"The message with Action 'http://tempuri.org/IWPCommunication/PageBreakRects'
cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher.
This may be because of either a contract mismatch (mismatched Actions between sender and receiver)
or a binding/security mismatch between the sender and the receiver.
Check that sender and receiver have the same contract and the same binding
(including security requirements, e.g. Message, Transport, None)."
It is worse mentioning, that if in function PageBreakRects replace:
DocDividionsResult br = WPService.PageBreakRects(docId, DocNum, PageNum);
with
DocDividionsResult br = WPService.GetPageDividions(docID, formId, pageNumber);
then no exception is thrown.
Not sure if you have started at the very beginning or not, but I expect that none of the code you posted is causing the error. That error means that you are having trouble calling your webservice from the client (silverlight) because there is an error in the system.serviceModel section in your web config. You can often fix it by just refreshing your service reference.
Try running the app locally in visual studio and point the service reference to the service you installed on the server (right click on the service reference and select Configure Service reference then change the URl to correspond to the service location on your server). If you are already developing/testing in this configuration try right clicking on the service reference and select "Update Service Reference".