/// <summary>
        /// Adds SQLFields to represent each field rule in the specified MappingsContext
        /// </summary>
        /// <param name="context"></param>
        /// <param name="dialect"></param>
        public void AddFields(MappingsContext context, Dialect dialect)
        {
            foreach (FieldMapping mapping in context.FieldMappings)
            {
                Rule rule = mapping.fRule;
                if (rule is XPathRule)
                {
                    TypeConverter converter = null;
                    XPathRule     xRule     = (XPathRule)rule;
                    IElementDef   targetDef = xRule.LookupTargetDef(context.ObjectDef);
                    if (targetDef != null)
                    {
                        converter = targetDef.TypeConverter;
                    }
                    if (converter == null)
                    {
                        converter = SifTypeConverters.STRING;
                    }
                    if (mapping.ValueSetID != null)
                    {
                        ValueSet vs = context.Mappings.GetValueSet(mapping.ValueSetID, true);
                        if (vs != null)
                        {
                            //Create the lookup table for generating the SQL lookup
                            StringBuilder buffer = new StringBuilder();
                            // e.g. CircRecord.PatronType{StudentPersonal=1;StaffPersonal=2}
                            //buffer.Append( tablePrefix );
                            buffer.Append(mapping.FieldName);
                            buffer.Append('{');
                            ValueSetEntry[] entries = vs.Entries;
                            for (int a = 0; a < entries.Length; a++)
                            {
                                if (a > 0)
                                {
                                    buffer.Append(';');
                                }
                                buffer.Append(entries[a].Value);
                                buffer.Append('=');
                                ;
                                buffer.Append(entries[a].Name);
                            }
                            buffer.Append('}');
                            SQLField f = new SQLField(buffer.ToString(), converter.DbType, dialect);
                            AddField(xRule.XPath, f);
                            continue;
                        }
                    }

                    SQLField field = new SQLField(mapping.FieldName, converter.DbType, dialect);
                    AddField(xRule.XPath, field);
                }
            }
        }
        public void testInBoundMappingContext50000()
        {
            fCfg = new AgentConfig();
            fCfg
            .Read(
                "..\\..\\Library\\Tools\\Mapping\\MultiVersion.agent.cfg",
                false);

            int mappingIterations = 0;
            //
            // UNCOMMENT THIS LINE TO RUN THE SPEED TEST
            //
            // mappingIterations = 50000;

            Mappings mappings = fCfg.Mappings.GetMappings("Default");

            // Fill out the student personal using outbound mappings first
            StudentPersonal template = new StudentPersonal();

            IDictionary      map = buildIDictionaryForStudentPersonalTest();
            StringMapAdaptor sma = new StringMapAdaptor(map);

            mappings.MapOutbound(sma, template);
            Console.WriteLine(template.ToXml());

            MappingsContext mc = mappings.SelectInbound(template.ElementDef,
                                                        SifVersion.SIF20, null, null);

            DateTime start = DateTime.Now;

            for (int x = 0; x < mappingIterations; x++)
            {
                map.Clear();
                mc.Map(template, sma);
                if (x % 500 == 0)
                {
                    Console.WriteLine("Iteration " + x + " of "
                                      + mappingIterations);
                }
            }

            DateTime end = DateTime.Now;

            Console.WriteLine("Mapping "
                              + mappingIterations
                              + " Students inbound took " + end.Subtract(start));
        }
示例#3
0
    /// <summary>  Handles SIF_Responses
    /// </summary>
    public virtual void OnQueryResults(IDataObjectInputStream inStream,
                                       SIF_Error error,
                                       IZone zone,
                                       IMessageInfo inf)
    {
        SifMessageInfo info = (SifMessageInfo)inf;

        Console.WriteLine
            ("\nReceived a query response from agent \"" + info.SourceId + "\" in zone " +
            zone.ZoneId);
        IRequestInfo reqInfo = info.SIFRequestInfo;

        if (reqInfo != null)
        {
            Console.WriteLine
                ("\nResponse was received in {0}. Object State is '{1}'",
                DateTime.Now.Subtract(reqInfo.RequestTime), reqInfo.UserData);
        }

        //
        //  Use the Mappings class to translate the LearnerPersonal objects received
        //  from the zone into a HashMap of field/value pairs, then dump the table
        //  to System.out
        //

        //  Always check for an error response
        if (error != null)
        {
            Console.WriteLine
                ("The request for LearnerPersonal failed with an error from the provider:");
            Console.WriteLine
                ("  [Category=" + error.SIF_Category + "; Code=" + error.SIF_Code + "]: " +
                error.SIF_Desc +
                ". " + error.SIF_ExtendedDesc);
            return;
        }

        //  Get the root Mappings object from the configuration file
        Mappings m = fCfg.Mappings.GetMappings("Default");

        //  Ask the root Mappings instance to select a Mappings from its
        //  hierarchy. For example, you might have customized the agent.cfg
        //  file with mappings specific to zones, versions of SIF, or
        //  requesting agents. The Mappings.select() method will select
        //  the most appropriate instance from the hierarchy given the
        //  three parameters passed to it.
        MappingsContext  mappings = m.SelectInbound(StudentDTD.STUDENTPERSONAL, info);
        Hashtable        data     = new Hashtable();
        StringMapAdaptor sma      = new StringMapAdaptor(data, Adk.Dtd.GetFormatter(SifVersion.LATEST));

        int count = 0;

        while (inStream.Available)
        {
            Console.WriteLine("Object Number {0}", count++);
            StudentPersonal sp = (StudentPersonal)inStream.ReadDataObject();
            //  Ask the Mappings object to populate the dictionary with field/value pairs
            //  by using the mapping rules in the configuration file to decompose
            //  the LearnerPersonal object into field values.
            mappings.Map(sp, sma);
            //  Now dump the field/value pairs to System.out
            DumpDictionaryToConsole(data);
            Console.WriteLine();
            data.Clear();
        }
    }
示例#4
0
    /// <summary>  Respond to SIF Requests
    /// </summary>
    public virtual void OnRequest(IDataObjectOutputStream outStream,
                                  Query query,
                                  IZone zone,
                                  IMessageInfo inf)
    {
        SifMessageInfo info  = (SifMessageInfo)inf;
        SifWriter      debug = new SifWriter(Console.Out);

        Console.WriteLine
            ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId +
            "\" in zone " + zone.ZoneId);

        // Tell the ADK to automatically filter out any objects that don't meet the requirements
        // of the query conditions
        outStream.Filter = query;

        //  Read all learners from the database to populate a HashMap of
        //  field/value pairs. The field names can be whatever we choose as long
        //  as they match the field names used in the <mappings> section of the
        //  agent.cfg configuration file. Each time a record is read, convert it
        //  to a LearnerPersonal object using the Mappings class and stream it to
        //  the supplied output stream.
        //
        IDictionary data    = new Hashtable();
        IDbCommand  command = null;

        Console.WriteLine("The SIF Request was requested in the following SIF Versions");
        foreach (SifVersion version in info.SIFRequestVersions)
        {
            Console.WriteLine("    - " + version);
        }

        Console.WriteLine("This agent will respond in its latest supported version, which is: ");
        Console.WriteLine("    - " + info.LatestSIFRequestVersion);

        //  Get the root Mappings object from the configuration file
        Mappings m =
            fCfg.Mappings.GetMappings("Default").Select
                (info.SourceId, zone.ZoneId, info.LatestSIFRequestVersion);

        //  Ask the root Mappings instance to select a Mappings from its
        //  hierarchy. For example, you might have customized the agent.cfg
        //  file with mappings specific to zones, versions of SIF, or
        //  requesting agents. The Mappings.selectOutbound() method will select
        //  the most appropriate instance from the hierarchy given the
        //  three parameters passed to it.
        MappingsContext mappings = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info);

        try
        {
            int count = 0;

            //  Query the database for all students
            command = fConn.CreateCommand();
            fConn.Open();
            command.CommandText = "SELECT * FROM Students";
            using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                DataReaderAdaptor dra = new DataReaderAdaptor(rs);
                while (rs.Read())
                {
                    count++;
                    //  Finally, create a new LearnerPersonal object and ask the
                    //  Mappings to populate it with SIF elements from the HashMap
                    //  of field/value pairs. As long as there is an <object>/<field>
                    //  definition for each entry in the HashMap, the ADK will take
                    //  care of producing the appropriate SIF element/attribute in
                    //  the LearnerPersonal object.
                    //
                    StudentPersonal sp = new StudentPersonal();
                    sp.RefId = Adk.MakeGuid();
                    mappings.Map(sp, dra);

                    //  Now write out the LearnerPersonal to the output stream and
                    //  we're done publishing this student.
                    //
                    Console.WriteLine("\nThe agent has read these values from the database:");
                    DumpDictionaryToConsole(data);
                    Console.WriteLine("To produce this LearnerPersonal object:");
                    debug.Write(sp);
                    debug.Flush();

                    outStream.Write(sp);
                    data.Clear();
                }

                rs.Close();
            }

            Console.WriteLine
                ("- Returned " + count + " records from the Student database in response");
        }
        catch (Exception ex)
        {
            Console.WriteLine("- Returning a SIF_Error response: " + ex.ToString());
            throw new SifException
                      (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1,
                      "An error occurred while querying the database for students", ex.ToString(), zone);
        }
        finally
        {
            if (command != null)
            {
                try
                {
                    fConn.Close();
                }
                catch (Exception ignored)
                {
                }
            }
        }
    }
示例#5
0
        /// <summary>  Respond to SIF RequestsGetTopicMap
        /// </summary>
        public virtual void OnRequest(IDataObjectOutputStream outStream,
                                      Query query,
                                      IZone zone,
                                      IMessageInfo inf)
        {
            SifMessageInfo info  = (SifMessageInfo)inf;
            SifWriter      debug = new SifWriter(Console.Out);

            Console.WriteLine
                ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId +
                "\" in zone " + zone.ZoneId);

            //  Read all students from the database to populate a HashMap of
            //  field/value pairs. The field names can be whatever we choose as long
            //  as they match the field names used in the <mappings> section of the
            //  agent.cfg configuration file. Each time a record is read, convert it
            //  to a StudentPersonal object using the Mappings class and stream it to
            //  the supplied output stream.
            //
            IDbCommand command = null;

            // Set a basic filter on the outgoing data stream
            // What will happen is that any object written to the output stream will
            // be evaluated based on the query conditions. If the object doesn't meet the
            // query conditions, it will be excluded
            outStream.Filter = query;

            //  Get the root Mappings object from the configuration file
            Edustructures.SifWorks.Tools.Mapping.Mappings m = fCfg.Mappings.GetMappings("Default");

            //  Ask the root Mappings instance to select a Mappings from its
            //  hierarchy. For example, you might have customized the agent.cfg
            //  file with mappings specific to zones, versions of SIF, or
            //  requesting agents. The Mappings.select() method will select
            //  the most appropriate instance from the hierarchy given the
            //  three parameters passed to it.
            //
            //IDictionary<string, string> dataMap = new System.Collections.Generic.Dictionary<string, string>();
            // IFieldAdaptor adaptor = new StringMapAdaptor(dataMap);
            //m.MapOutbound();
            MappingsContext mc = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info);

            try {
                int count = 0;

                //  Query the database for all students
                command = fConn.CreateCommand();
                fConn.Open();
                command.CommandText = "SELECT * FROM Students";
                using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection)) {
                    DataReaderAdaptor dra = new DataReaderAdaptor(rs);

                    while (rs.Read())
                    {
                        //  Finally, create a new StudentPersonal object and ask the
                        //  Mappings to populate it with SIF elements from the HashMap
                        //  of field/value pairs. As long as there is an <object>/<field>
                        //  definition for each entry in the HashMap, the ADK will take
                        //  care of producing the appropriate SIF element/attribute in
                        //  the StudentPersonal object.
                        //
                        StudentPersonal sp = new StudentPersonal();
                        sp.RefId = Adk.MakeGuid();
                        // TODO: When using custom macros for outboud mapping operations, set the ValueBuilder.
                        // You will need to call SetValueBuilder() giving the MappingsContext a derived version
                        // of DefaultValueBuilder that has the macro methods available in it.
                        mc.SetValueBuilder(new DataUtilMacro(dra));
                        mc.Map(sp, dra);

                        //  Now write out the StudentPersonal to the output stream and
                        //  we're done publishing this student.
                        //
                        Console.WriteLine("\nThe agent has read these values from the database:");

                        DumpFieldsToConsole(rs);
                        Console.WriteLine("To produce this StudentPersonal object:");
                        debug.Write(sp);
                        debug.Flush();

                        outStream.Write(sp);
                    }

                    rs.Close();
                }
                Console.WriteLine
                    ("- Returned " + count + " records from the Student database in response");
            } catch (Exception ex) {
                Console.WriteLine("- Returning a SIF_Error response: " + ex);
                throw new SifException
                          (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1,
                          "An error occurred while querying the database for students", ex.ToString(), zone);
            } finally {
                if (command != null)
                {
                    try {
                        fConn.Close();
                    } catch (Exception ignored) {
                        Log.Warn(ignored.Message, ignored);
                    }
                }
            }
        }
 /// <summary>
 /// Adds SQLFields to represent each field rule in the specified MappingsContext.
 /// </summary>
 /// <param name="context"></param>
 public void AddFields(MappingsContext context)
 {
     AddFields(context, SqlDialect.DEFAULT);
 }