void CreateLocalPlayers() { string homeNamespace = "ai.pkr.metabots.bots."; string homeAssembly = Assembly.GetExecutingAssembly().FullName; foreach (LocalPlayerCfg localBotCfg in Configuration.LocalPlayers) { string type = localBotCfg.Type.Get(Props.Global); if (type.StartsWith(homeNamespace) && localBotCfg.Assembly.Get(Props.Global) == "") { type += ", " + homeAssembly; } IPlayer iplayer = ClassFactory.CreateInstance <IPlayer>(type, localBotCfg.Assembly.Get(Props.Global)); if (iplayer != null) { Props creationParams = localBotCfg.CreationParameters; if (Configuration.XmlParams != null && Configuration.XmlParams.XmlFile != null) { creationParams.Set("pkr.SessionSuiteXmlFileName", Configuration.XmlParams.XmlFile); } iplayer.OnCreate(localBotCfg.Name, creationParams); AddLocalPlayer(iplayer, localBotCfg.Name); } } }
// TODO: Implement /* * * private SIF_Request createSIF_Request( ElementDef objectType, String refId, Zone zone ) * { * SIF_Request request = new SIF_Request(); * request.getHeader().setSIF_MsgId( MSG_GUID ); * request.getHeader().setSIF_SourceId( "foo" ); * request.setSIF_MaxBufferSize("32768"); * request.setSIF_Version( ADK.getSIFVersion().toString() ); * Query query = new Query(objectType); * query.addCondition(SifDtd.SIF_REPORTOBJECT_REFID, Condition.EQ, refId); * * SIF_Query q = SIFPrimitives.createSIF_Query(query, zone); * SIF_QueryObject sqo = new SIF_QueryObject(); * sqo.setObjectName( objectType.name() ); * * q.setSIF_QueryObject(sqo); * request.setSIF_Query(q); * * return request; * } * */ private SIF_Response createSIF_Response(IElementDef objType, bool storeInRequestCache, ISerializable stateObject) { SIF_Request req = createSIF_Request(objType); if (storeInRequestCache) { Query q = new Query(objType); q.UserData = stateObject; RequestCache.GetInstance(fAgent).StoreRequestInfo(req, q, fZone); } SIF_Response resp = new SIF_Response(); resp.SIF_RequestMsgId = req.Header.SIF_MsgId; SIF_ObjectData sod = new SIF_ObjectData(); resp.SIF_ObjectData = sod; Object responseObject = null; try { responseObject = ClassFactory.CreateInstance(objType.FQClassName, false); } catch (Exception cfe) { throw new AdkException("Unable to create instance of " + objType.Name, fZone, cfe); } sod.AddChild((SifElement)responseObject); return(resp); }
private SIF_Event createSIF_Event(IElementDef objType) { SIF_Event evnt = new SIF_Event(); evnt.Header.SIF_SourceId = "foo"; SIF_ObjectData sod = new SIF_ObjectData(); SIF_EventObject obj = new SIF_EventObject(); obj.ObjectName = objType.Name; sod.SIF_EventObject = obj; evnt.SIF_ObjectData = sod; obj.Action = EventAction.Add.ToString(); Object eventObject = null; try { eventObject = ClassFactory.CreateInstance(objType.FQClassName); } catch (Exception cfe) { throw new AdkException("Unable to create instance of " + objType.Name, fZone, cfe); } obj.AddChild(objType, (SifElement)eventObject); return(evnt); }
private void ReadInternal(BinaryReader r) { Version = new BdsVersion(); Version.Read(r); int serFmtVer = r.ReadInt32(); if (serFmtVer > SERIALIZATION_FORMAT_VERSION) { throw new ApplicationException(string.Format( "Unsupported serialization format: {0}, max supported: {1}", serFmtVer, SERIALIZATION_FORMAT_VERSION)); } if (serFmtVer == 1) { throw new ApplicationException("Serialization format version 1 is not supported"); } int nodeSerFmtVer = 0; if (serFmtVer >= 3) { nodeSerFmtVer = r.ReadInt32(); } IClusterNode root; string typeName = r.ReadString(); ClassFactoryParams p = new ClassFactoryParams(typeName, ""); root = ClassFactory.CreateInstance <IClusterNode>(p); root.Read(r, nodeSerFmtVer); Root = root; }
static IGameLogReport CreateGameLogReport(string name) { IGameLogReport rep; if (String.IsNullOrEmpty(_cmdLine.ReportClass)) { rep = new TotalResult(); } else { ClassFactoryParams cfp = new ClassFactoryParams(_cmdLine.ReportClass); rep = ClassFactory.CreateInstance <IGameLogReport>(cfp); } rep.Name = name; rep.Configure(_reportParameters); // Show help only once if (_cmdLine.ShowReportHelp && !_isHelpShown) { rep.ShowHelp(_output); _isHelpShown = true; } return(rep); }
public static ObjectFactory GetInstance() { if (sInstance == null) { String cls = ConfigurationManager.AppSettings[OBJECT_FACTORY_CLASS]; if (String.IsNullOrEmpty(cls)) { sInstance = new ObjectFactoryImpl(); } else { try { sInstance = (ObjectFactory)ClassFactory.CreateInstance(cls); } catch (Exception thr) { throw new Exception( "ADK could not create an instance of the class " + cls + ": " + thr, null); } } } return(sInstance); }
public Form1() { InitializeComponent(); Type type = Type.GetTypeFromProgID("Program.Server"); ClassFactory cF = new ClassFactory(); IntPtr ptr_object; Guid guid = type.GUID; cF.CreateInstance(IntPtr.Zero, ref guid, out ptr_object); obj = Marshal.GetObjectForIUnknown(ptr_object); List <double[]> list = new List <double[]>(); object[] param = new object[] { -2, 10 }; list.AddRange((IEnumerable <double[]>)obj.GetType().InvokeMember("GetAllPoint", BindingFlags.InvokeMethod, null, obj, param)); PointPairList pList = new PointPairList(); for (int i = 0; i < list.Count; i++) { pList.Add(list[i][0], list[i][1]); } #region DrawGraph GraphPane pane = zedGraphControl.GraphPane; pane.CurveList.Clear(); pane.XAxis.Scale.Min = pList[0].X; pane.XAxis.Scale.Max = pList[pList.Count - 1].X; LineItem myCurve = pane.AddCurve("Значения функции f(x) от x", pList, Color.Blue, SymbolType.None); pane.XAxis.Title.Text = "Значениe x"; pane.YAxis.Title.Text = "Значение функции"; pane.Title.Text = "Значения функции на отрезке от -2 до 10"; pane.Fill = new Fill(Color.White, Color.LightSkyBlue, 45.0f); pane.Chart.Fill.Type = FillType.None; zedGraphControl.AxisChange(); zedGraphControl.Invalidate(); #endregion }
/// <summary> Get a RequestCache instance</summary> public static RequestCache GetInstance(Agent agent) { if (sSingleton == null) { String cls = Properties.GetProperty("adkglobal.factory.RequestCache"); try { if (cls == null) { sSingleton = new RequestCacheFile(); } else { sSingleton = (RequestCache)ClassFactory.CreateInstance(cls); } sSingleton.Initialize(agent); } catch (Exception thr) { sSingleton = null; throw new AdkException ("Adk could not create an instance of the class " + cls + ": " + thr, null, thr); } } return(sSingleton); }
private static IUnknown NewRedemptionObject(Guid guid) { //try to set the thread COM apartment //Thread.CurrentThread.ApartmentState = ApartmentState.STA; object res = null; lock (_criticalSection) { IClassFactory ClassFactory; if (_redemptionDllHandle.Equals(IntPtr.Zero)) { string dllPath; if (IntPtr.Size == 8) { dllPath = DllLocation64Bit; } else { dllPath = DllLocation32Bit; } _redemptionDllHandle = Win32NativeMethods.LoadLibraryW(dllPath); if (_redemptionDllHandle.Equals(IntPtr.Zero)) { //throw new Exception(string.Format("Could not load '{0}'\nMake sure the dll exists.", dllPath)); throw new Win32Exception(Marshal.GetLastWin32Error()); } _dllGetClassObjectPtr = Win32NativeMethods.GetProcAddress(_redemptionDllHandle, "DllGetClassObject"); if (_dllGetClassObjectPtr.Equals(IntPtr.Zero)) { //throw new Exception("Could not retrieve a pointer to the 'DllGetClassObject' function exported by the dll"); throw new Win32Exception(Marshal.GetLastWin32Error()); } _dllGetClassObject = (DllGetClassObject) Marshal.GetDelegateForFunctionPointer(_dllGetClassObjectPtr, typeof(DllGetClassObject)); } Object unk; int hr = _dllGetClassObject(ref guid, ref IID_IClassFactory, out unk); if (hr != 0) { throw new Exception("DllGetClassObject failed with error code 0x" + hr.ToString("x8")); } ClassFactory = unk as IClassFactory; ClassFactory.CreateInstance(null, ref IID_IUnknown, out res); //If the same class factory is returned as the one still //referenced by .Net, the call will be marshalled to the original thread //where that class factory was retrieved first. //Make .Net forget these objects Marshal.ReleaseComObject(unk); Marshal.ReleaseComObject(ClassFactory); } //lock return(res as IUnknown); }
public void Test_CreateByAssemblyName_BaseClass() { string typeName = "ai.lib.utils.nunit.ClassFactory_Test+TestClass1,ai.lib.utils.nunit"; ClassFactoryParams p = new ClassFactoryParams { TypeName = typeName }; TestClass1 tc = (TestClass1)ClassFactory.CreateInstance <TestClassBase>(p); Assert.IsNotNull(tc); }
public void Test_CreateByAssemblyFileAndAssemblyName_AnotherAssembly() { string typeName = "ai.lib.utils.testlib.DerivedTestClass1, ai.lib.utils.testlib"; ClassFactoryParams p = new ClassFactoryParams { AssemblyFile = "", TypeName = typeName }; TestClassBase tc = ClassFactory.CreateInstance <TestClassBase>(p); Assert.IsNotNull(tc); }
public void Test_CreateByAssemblyFile_BaseClass() { string assemblyFile = Path.GetFileName(CodeBase.Get(Assembly.GetExecutingAssembly())); string typeName = "ai.lib.utils.nunit.ClassFactory_Test+TestClass1"; ClassFactoryParams p = new ClassFactoryParams { AssemblyFile = assemblyFile, TypeName = typeName }; TestClass1 tc = (TestClass1)ClassFactory.CreateInstance <TestClassBase>(p); Assert.IsNotNull(tc); }
static IPlayer CreatePlayer() { ClassFactoryParams cfp = new ClassFactoryParams(_cmdLine.BotClass.Get(Props.Global)); IPlayer iplayer = ClassFactory.CreateInstance <IPlayer>(cfp); if (iplayer != null) { Props creationParams = XmlSerializerExt.Deserialize <Props>(_cmdLine.CreationParametersFileName.Get(Props.Global)); iplayer.OnCreate(_botName, creationParams); } return(iplayer); }
public void Test_CreateByAssemblyName_Params() { string typeName = "ai.lib.utils.nunit.ClassFactory_Test+TestClass2,ai.lib.utils.nunit"; ClassFactoryParams p = new ClassFactoryParams { TypeName = typeName, Arguments = new object[] { 113, "bla-bla" } }; TestClass2 tc = ClassFactory.CreateInstance <TestClass2>(p); Assert.IsNotNull(tc); Assert.AreEqual(113, tc.P1); Assert.AreEqual("bla-bla", tc.P2); }
public void Test_CreateByAssemblyFile_NonReferencedAssembly() { string assemblyFile = "ai.lib.utils.testlib.dll"; string assemblyName = Path.GetFileNameWithoutExtension(assemblyFile); // First do not use assembly name in the type name string typeName = "ai.lib.utils.testlib.DerivedTestClass1"; ClassFactoryParams p = new ClassFactoryParams { AssemblyFile = assemblyFile, TypeName = typeName }; TestClassBase tc = ClassFactory.CreateInstance <TestClassBase>(p); Assert.IsNotNull(tc); }
public void Test_CreateByAssemblyFile_Params() { string assemblyFile = Path.GetFileName(CodeBase.Get(Assembly.GetExecutingAssembly())); string typeName = "ai.lib.utils.nunit.ClassFactory_Test+TestClass2"; ClassFactoryParams p = new ClassFactoryParams { AssemblyFile = assemblyFile, TypeName = typeName, Arguments = new object[] { 113, "bla-bla" } }; TestClass2 tc = ClassFactory.CreateInstance <TestClass2>(p); Assert.IsNotNull(tc); Assert.AreEqual(113, tc.P1); Assert.AreEqual("bla-bla", tc.P2); }
public static IChanceAbstraction CreateFromProps(Props props) { ClassFactoryParams cfp = new ClassFactoryParams { TypeName = props.Get("TypeName"), AssemblyFile = props.Get("AssemblyFileName"), Arguments = new object[] { props } }; if (string.IsNullOrEmpty(cfp.TypeName)) { throw new ApplicationException("Missing required property 'TypeName'"); } IChanceAbstraction ca = ClassFactory.CreateInstance <IChanceAbstraction>(cfp); return(ca); }
/// <summary> Construct a new DataObjectOutputStream</summary> /// <returns> A new DataObjectOutputStream object, which will always be a /// an instanceof DataObjectOutputStreamImpl as defined by the /// <c>adkglobal.factory.DataObjectOutputStream</c> system property. /// /// </returns> public static DataObjectOutputStreamImpl NewInstance() { String cls = Properties.GetProperty("adkglobal.factory.DataObjectOutputStream"); if (cls == null) { return(new DataObjectOutputFileStream()); } else { try { return((DataObjectOutputStreamImpl)ClassFactory.CreateInstance(cls)); } catch (Exception thr) { throw new AdkException ("Adk could not create an instance of the class " + cls + ": " + thr, null, thr); } } }
public void ConstructFromXml(ConstructFromXmlParams parameters) { if (GameRulesType != null) { string typeName = GameRulesType.Get(parameters.Local); string assemblyFileName = GameRulesAssemblyFile.Get(parameters.Local); if (typeName != "") { IGameRules gameRules = ClassFactory.CreateInstance <IGameRules>(typeName, assemblyFileName); gameRules.OnCreate(GameRulesCreationParams); GameRules = gameRules; } } if (DeckDescrFile != null) { string deckFile = DeckDescrFile.Get(parameters.Local); if (deckFile != "") { DeckDescr = XmlSerializerExt.Deserialize <DeckDescriptor>(deckFile); } } }
static IPlayer CreatePlayer() { ClassFactoryParams cfp = new ClassFactoryParams(_cmdLine.BotClass.Get(Props.Global)); IPlayer iplayer = ClassFactory.CreateInstance <IPlayer>(cfp); if (iplayer != null) { Props creationParams = XmlSerializerExt.Deserialize <Props>(_cmdLine.CreationParametersFileName.Get(Props.Global)); iplayer.OnCreate(BotName, creationParams); PlayerInfo pi = iplayer.OnServerConnect(); if (_cmdLine.Verbose) { Console.WriteLine("Player.OnServerConnect() returned:"); Console.WriteLine("Name: {0}", pi.Name); Console.WriteLine("Version: {0}", pi.Version); } iplayer.OnSessionBegin(SessionName, null, null); } return(iplayer); }
private void ParseLegacyXML( XmlReader reader, SifVersion version, IZone zone, SifElement currentElement, SifFormatter formatter, String xmlName) { bool handled = false; // Determine if any surrogate formatters that are defined as children // of the current element can resolve it // NOTE: Until we fix this in the ADK, elements from the common package loose their // metadata information that was originally defined. IElementDef currentDef = currentElement.ElementDef; IList <IElementDef> children = currentDef.Children; if (children == null || children.Count == 0) { // try to get the actual element def // WARNING! this is somewhat of a hack until // we get support for what we need in the ADK metadata try { SifElement copy = (SifElement)ClassFactory.CreateInstance(currentDef.FQClassName); children = copy.ElementDef.Children; } catch (Exception cnfe) { throw new SifException( SifErrorCategoryCode.Xml, SifErrorCodes.XML_GENERIC_VALIDATION_3, "Unable to parse" + xmlName + " " + version.ToString() + cnfe.Message, zone); } } using (XmlReader subtreeReader = reader.ReadSubtree()) { subtreeReader.Read(); foreach (IElementDef candidate in children) { if (candidate.EarliestVersion.CompareTo(version) > 0) { continue; } IElementVersionInfo evi = candidate.GetVersionInfo(version); if (evi != null) { IRenderSurrogate rs = evi.GetSurrogate(); if (rs != null) { try { bool surrogateHandled = rs.ReadRaw(subtreeReader, version, currentElement, formatter); if (surrogateHandled) { handled = true; break; } } catch (AdkTypeParseException e) { HandleTypeParseException("Unable to parse element or attribute value: " + e.Message, e, zone); handled = true; break; } catch (AdkParsingException e) { throw new SifException(SifErrorCategoryCode.Xml, SifErrorCodes.XML_GENERIC_VALIDATION_3, "unable to parse xml: " + e.Message + version.ToString(), zone); } } } } subtreeReader.Close(); } // advance to the next tag reader.Read(); if (!handled) { String _tag = currentElement != null ? currentElement.ElementDef.Name + "/" + xmlName : xmlName; throw new SifException( SifErrorCategoryCode.Xml, SifErrorCodes.XML_GENERIC_VALIDATION_3, "Unknown element or attribute", _tag + " is not a recognized element of SIF " + version.ToString(), zone); } }
/// <summary> Initialize and start the agent /// </summary> /// <param name="args">Command-line arguments (run with no arguments to display help) /// /// </param> public virtual void startAgent(string[] args) { Name = "SIFWorks ADK Example"; Console.WriteLine("Initializing agent..."); // Read the configuration file fCfg = new AgentConfig(); Console.WriteLine("Reading configuration file..."); fCfg.Read("agent.cfg", false); // Override the SourceId passed to the constructor with the SourceId // specified in the configuration file Id = fCfg.SourceId; // Inform the ADK of the version of SIF specified in the sifVersion= // attribute of the <agent> element SifVersion version = fCfg.Version; //SifVersion version = SifVersion.SIF15r1; Adk.SifVersion = version; // Now call the superclass initialize once the configuration file has been read base.Initialize(); // // Ask the AgentConfig instance to "apply" all configuration settings // to this Agent; for example, all <property> elements that are children // of the root <agent> node are parsed and applied to this Agent's // AgentProperties object; all <zone> elements are parsed and registered // with the Agent's ZoneFactory, and so on. // fCfg.Apply(this, true); // Establish the ODBC connection to the Students.mdb database file. // The JDBC driver and URL are specified in the agent.cfg configuration // file and were automatically added to the AgentProperties when the // apply method was called above. // Console.WriteLine("Opening database..."); AgentProperties props = Properties; string driver = props.GetProperty("Connection"); string url = props.GetProperty("ConnectionString"); Console.WriteLine("- Using driver: " + driver); Console.WriteLine("- Connecting to URL: " + url); // Load the DataDriver driver // Get a Connection fConn = (IDbConnection)ClassFactory.CreateInstance(driver); fConn.ConnectionString = url; // Connect to each zone specified in the configuration file, registering // this agent as the Provider of StudentPersonal objects. Once connected, // send a request for StudentPersonal. // Console.WriteLine("Connecting to zones and requesting StudentPersonal objects..."); IZone[] allZones = ZoneFactory.GetAllZones(); for (int i = 0; i < allZones.Length; i++) { try { // Connect to this zone Console.WriteLine ("- Connecting to zone \"" + allZones[i].ZoneId + "\" at " + allZones[i].ZoneUrl); allZones[i].SetPublisher(this, StudentDTD.STUDENTPERSONAL, null); allZones[i].SetQueryResults(this); allZones[i].Connect(ProvisioningFlags.Register); // Request all students Query q = new Query(StudentDTD.STUDENTPERSONAL); q.UserData = "Mappings Demo"; allZones[i].Query(q); } catch (AdkException ex) { Console.WriteLine(" " + ex.Message); } } }