Example #1
0
        /// <summary>
        /// Generate String from requestMessage
        /// </summary>
        /// <param name="request">request message</param>
        /// <returns>request message in serialized form</returns>
        private string GenerateStringFromRequest(RequestMessage request)
        {
            StringBuilder requestStringBuilder = new StringBuilder();

            SimplTypesScope.Serialize(request, requestStringBuilder, StringFormat.Xml);
            return(requestStringBuilder.ToString());
        }
        private async void BtnGetMetadata_Click(object sender, RoutedEventArgs e)
        {
            //            string serializedMetadata = UrlBox.Text;
            //            Object o = RepositoryMetadataTranslationScope.Get().Deserialize(serializedMetadata, StringFormat.Xml);
            //            StringBuilder sb = new StringBuilder();
            //            SimplTypesScope.Serialize(o, sb, StringFormat.Xml);
            //            String reserializedMetadatata = sb.ToString();
            //            Console.WriteLine(reserializedMetadatata);
            //Expander expander = new Expander();
            //TextBox metadataXML = new TextBox { TextWrapping = TextWrapping.Wrap, MinHeight = 100 };
            //metadataXML.Text = reserializedMetadatata;

            string urls = UrlBox.Text;

            List <Task <Document> >          extractionRequests = new List <Task <Document> >();
            Dictionary <ParsedUri, DateTime> timeStamps         = new Dictionary <ParsedUri, DateTime>();

            foreach (var s in urls.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
            {
                Console.WriteLine("Requesting async extraction of: " + s);

                ParsedUri puri = new ParsedUri(s);
                {
                    Task <Document> t = _semanticsSessionScope.GetDocument(puri);
                    timeStamps.Add(puri, DateTime.Now);
                    //Alternate, if you want the document here:
                    //Document doc = await _semanticsSessionScope.GetDocument(puri);

                    extractionRequests.Add(t);
                }
            }

            while (extractionRequests.Count > 0)
            {
                Task <Document> completedTask = await Task.WhenAny(extractionRequests);

                extractionRequests.Remove(completedTask);

                Document parsedDoc = await completedTask;
                if (parsedDoc == null)
                {
                    continue;
                }

                Expander expander = new Expander {
                    Header = parsedDoc.Title
                };
                TextBox metadataXML = new TextBox {
                    TextWrapping = TextWrapping.Wrap, MinHeight = 100
                };

                var s = timeStamps[parsedDoc.Location.Value];
                Console.WriteLine(" ---------------------------------- Time to complete: " +
                                  DateTime.Now.Subtract(s).TotalMilliseconds);
                metadataXML.Text = await Task.Run(() => SimplTypesScope.Serialize(parsedDoc, StringFormat.Xml));

                expander.Content = metadataXML;
                MetadataTitleXMLContainer.Children.Add(expander);
            }
        }
        /// <summary>
        /// helper function to generate and send byte array message to client session.
        /// </summary>
        /// <param name="uid">uid of the received message</param>
        /// <param name="message">oodss message</param>
        /// <param name="session">client's websocket session</param>
        ///
        /// out message format
        ///  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .......n
        /// |length |      uid        |        message ....|
        ///
        private void CreatePacketFromMessageAndSend(long uid, ServiceMessage message, WebSocketSession session)
        {
            StringBuilder responseMessageStringBuilder = new StringBuilder();

            SimplTypesScope.Serialize(message, responseMessageStringBuilder, StringFormat.Xml);
            string req = responseMessageStringBuilder.ToString();

            //Console.WriteLine("send message: "+ req + " uid "+uid);

            byte[] uidBytes     = BitConverter.GetBytes(uid);
            byte[] messageBytes = Encoding.UTF8.GetBytes(req);
            byte[] lengthBytes  = BitConverter.GetBytes(uidBytes.Length + messageBytes.Length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(lengthBytes);
            }
            byte[] outMessage = new byte[lengthBytes.Length + uidBytes.Length + messageBytes.Length];

            Buffer.BlockCopy(lengthBytes, 0, outMessage, 0, lengthBytes.Length);
            Buffer.BlockCopy(uidBytes, 0, outMessage, lengthBytes.Length, uidBytes.Length);
            Buffer.BlockCopy(messageBytes, 0, outMessage, lengthBytes.Length + uidBytes.Length, messageBytes.Length);

            session.SendResponse(outMessage);
            //session.SendResponseAsync(Encoding.UTF8.GetString(outMessage));
        }
        public static string GetJsonMMD(MetaMetadata mmd)
        {
            if (mmd == null)
            {
                return(null);
            }

            string result = null;

            lock (mmdJSONCache)
            {
                mmdJSONCache.TryGetValue(mmd, out result);
            }
            if (result == null)
            {
                StringBuilder mmdJSON = new StringBuilder();
                mmdJSON.Append("mmd = ");
                mmdJSON.Append(SimplTypesScope.Serialize(mmd, StringFormat.Json));
                mmdJSON.Append(";");
                result = mmdJSON.ToString();
                lock (mmdJSONCache)
                {
                    mmdJSONCache.Add(mmd, result);
                }
            }
            return(result);
        }
Example #5
0
        private string MessageForXml(ElementState requestObj, int uidUsed)
        {
            string msg = SimplTypesScope.Serialize(requestObj, StringFormat.Xml);
            string ret = String.Format("content-length:{0}\r\nuid:{1}\r\n\r\n{2}", msg.Length, uidUsed, msg);

            return(ret);
        }
Example #6
0
        public static void Main(string[] args)
        {
            Book abook = new Book();

            //Here's an instance of our type to serialize

            abook.setAuthorName("Michael Feathers");
            abook.setBookID(1337);
            abook.setTitle("Working Effectively with Legacy Code");
            //
            //

            SimplTypesScope book_example_sts = new SimplTypesScope("book_example", typeof(Book));

            //Serialize to JSON
            String jsonResult = SimplTypesScope.Serialize(abook, StringFormat.Json);

            //Serialize to XML
            // (Just change the StringFormat parameter!)
            String xmlResult = SimplTypesScope.Serialize(abook, StringFormat.Xml);

            Object result1 = book_example_sts.Deserialize(jsonResult, StringFormat.Json);
            Book   r1      = (Book)result1;

            Object result2 = book_example_sts.Deserialize(xmlResult, StringFormat.Xml);
            Book   r2      = (Book)result2;

            Console.WriteLine(jsonResult);

            Console.WriteLine(xmlResult);
            Console.ReadLine();
        }
Example #7
0
        public void NotConditionTest()// throws SIMPLTranslationException
        {
            String       xml = "<not><and><or><and /><or /></or><not_null /></and></not>";
            NotCondition not = (NotCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml);

            Console.WriteLine(not);
            Console.WriteLine(not.Check);
            Console.WriteLine(SimplTypesScope.Serialize(not, StringFormat.Xml));
        }
Example #8
0
        public void OrConditionTest()// throws SIMPLTranslationException
        {
            String      xml = "<or><or /><not_null /></or>";
            OrCondition or  = (OrCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml);

            Console.WriteLine(or);
            Console.WriteLine(or.Checks);
            Console.WriteLine(SimplTypesScope.Serialize(or, StringFormat.Xml));
        }
Example #9
0
        public void AndConditionTest()
        {
            String       xml = "<and><or><and /><or /></or><not_null /></and>";
            AndCondition and = (AndCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml);

            Console.WriteLine(and);
            Console.WriteLine(and.Checks);
            Console.WriteLine(SimplTypesScope.Serialize(and, StringFormat.Xml));
        }
Example #10
0
        public async Task <MetaMetadataRepository> LoadRepositoryFromServiceAsync(ParsedUri serviceUri, object cacheFile = null)
        {
            _metaMetadataRepository = (serviceUri != null) ? await RequestMetaMetadataRepository(new ParsedUri(serviceUri, "mmdrepository.xml")) : new MetaMetadataRepository();

            if (cacheFile != null)
            {
                SimplTypesScope.Serialize(_metaMetadataRepository, cacheFile, Format.Xml);
            }

            InitializeRepositoryAndPerformBinding();

            return(_metaMetadataRepository);
        }
Example #11
0
        /// <summary>
        /// serializes data and returns an the serialized data as a stream for application to use.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static HelperStream TestSerialization(Object obj, Format format)
        {
            HelperStream hStream = new HelperStream();

            SimplTypesScope.Serialize(obj, hStream, format);

            /*switch (format)
             * {
             *  case Format.Tlv:
             *      PrettyPrint.PrintBinary(hStream.BinaryData, format);
             *      break;
             *  default:
             *      PrettyPrint.PrintString(hStream.StringData, format);
             *      break;
             * }*/
            Console.WriteLine(Encoding.UTF8.GetString(hStream.ToArray()));
            return(new HelperStream(hStream.BinaryData));
        }
Example #12
0
        public void TestMethod1()
        {
            Book abook = new Book();

            //Here's an instance of our type to serialize

            abook.initBook();
            //
            //

            SimplTypesScope book_example_sts = new SimplTypesScope("book_example", typeof(Book));

            //Serialize to JSON
            String jsonResult = SimplTypesScope.Serialize(abook, StringFormat.Json);

            //Serialize to XML
            // (Just change the StringFormat parameter!)
            String xmlResult = SimplTypesScope.Serialize(abook, StringFormat.Xml);

            Object result1 = book_example_sts.Deserialize(jsonResult, StringFormat.Json);
            Book   r1      = (Book)result1;

            Object result2 = book_example_sts.Deserialize(xmlResult, StringFormat.Xml);
            Book   r2      = (Book)result2;

            Assert.IsTrue(result1.GetType().IsAssignableFrom(abook.GetType()));

            Assert.AreEqual(r1.getAuthor(), abook.getAuthor());
            Assert.AreEqual(r1.getBookID(), abook.getBookID());
            Assert.AreEqual(r1.getTitle(), abook.getTitle());

            Assert.AreEqual(r1.getAuthor(), "Michael Feathers");
            Assert.AreEqual(r1.getBookID(), 1337);
            Assert.AreEqual(r1.getTitle(), "Working Effectively with Legacy Code");

            Assert.AreEqual(r2.getAuthor(), abook.getAuthor());
            Assert.AreEqual(r2.getBookID(), abook.getBookID());
            Assert.AreEqual(r2.getTitle(), abook.getTitle());
        }
Example #13
0
        public void SemanticOperationTest()// throws SIMPLTranslationException
        {
            String collectedExampleUrlMetadata         = @"..\..\..\..\..\MetaMetadataRepository\MmdRepository\testData\collectedExampleUrlMetadata.xml";
            String collectedExampleUrlMetadataNoAuthor = @"..\..\Data\InformationCompositionDeclarationExample.xml";
            String useAuthor = @"..\..\Data\InformationCompositionDeclarationUseAuthor.xml";

            SimplTypesScope _repositoryMetadataTranslationScope = RepositoryMetadataTranslationScope.Get();

            SemanticsGlobalScope _semanticsSessionScope = new SemanticsSessionScope(
                _repositoryMetadataTranslationScope,
                MetaMetadataRepositoryInit.DEFAULT_REPOSITORY_LOCATION);

            InformationCompositionDeclaration doc = (InformationCompositionDeclaration)_repositoryMetadataTranslationScope.DeserializeFile(collectedExampleUrlMetadata, Format.Xml);

            foreach (Metadata metadata in doc.Metadata)
            {
                MetaMetadata metaMetadata = (MetaMetadata)metadata.MetaMetadata;

                SemanticOperationHandler handler = new SemanticOperationHandler(_semanticsSessionScope, null);
                handler.TakeSemanticOperations(metaMetadata, metadata, metaMetadata.SemanticActions);
            }

            Console.WriteLine(SimplTypesScope.Serialize(doc, StringFormat.Xml));
        }
Example #14
0
        public void TestSemanticServiceError()
        {
            SimplTypesScope repositoryMetadataTranslationScope = RepositoryMetadataTranslationScope.Get();

            SimplTypesScope typesScope = SimplTypesScope.Get("MetadataServicesTranslationScope",
                                                             repositoryMetadataTranslationScope,
                                                             typeof(MetadataRequest),
                                                             typeof(MetadataResponse),
                                                             typeof(SemanticServiceError));
            String response = "<semantic_service_error code=\"2001\" error_message=\"Error\" />";

            ServiceMessage serviceMessage = (ServiceMessage)typesScope.Deserialize(response, StringFormat.Xml);

            try
            {
                (serviceMessage as SemanticServiceError).Perform();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine(SimplTypesScope.Serialize(serviceMessage, StringFormat.Xml));
        }
Example #15
0
        public void HandleForLoop(ForEachSemanticOperation operation, DocumentParser parser,
                                  SemanticsGlobalScope infoCollector)
        {
            try
            {
                // get all the action which have to be performed in loop
                List <SemanticOperation> nestedSemanticActions = operation.NestedSemanticActionList;

                // get the collection object name on which we have to loop
                String collectionObjectName = operation.Collection;
                // if(checkPreConditionFlagsIfAny(action))
                {
                    Object collectionObject = semanticOperationVariableMap.Get(collectionObjectName);

                    if (collectionObject == null)
                    {
                        Debug.WriteLine("Can't execute loop because collection is null: " + SimplTypesScope.Serialize(operation, StringFormat.Xml));
                        return;
                    }

                    // get the objects from the collection object

                    /*                    List<Object> collection = new List<Object>();
                     *                  foreach (Object value in (IEnumerable)collectionObject)
                     *                  {
                     *                      collection.Add(value);
                     *                  }
                     */
                    int collectionSize = ((IList)collectionObject).Count;

                    // set the size of collection in the for loop action.
                    if (operation.Size != null)
                    {
                        // we have the size value. so we add it in parameters
                        semanticOperationVariableMap.Put(operation.Size, collectionSize);
                    }

                    int start = 0;
                    int end   = collectionSize;

                    if (operation.Start != null)
                    {
                        start = Int32.Parse(operation.Start);
                    }
                    if (operation.End != null)
                    {
                        end = Int32.Parse(operation.End);
                    }

                    if (GetOperationState(operation, "state", SemanticOperation.INIT) == SemanticOperation.INTER)
                    {
                        start = GetOperationState(operation, "current_index", 0);
                    }

                    SetOperationState(operation, "state", SemanticOperation.INTER);

                    // start the loop over each object
                    for (int i = start; i < end; i++)
                    {
                        SetOperationState(operation, "current_index", i);
                        Object item = ((IList)collectionObject)[i];
                        // put it in semantic action return value map
                        semanticOperationVariableMap.Put(operation.AsStr, item);

                        // see if current index is needed
                        if (operation.CurrentIndex != null)
                        {
                            // set the value of this variable in parameters
                            semanticOperationVariableMap.Put(operation.CurrentIndex, i);
                        }

                        // now take all the actions nested inside for loop
                        foreach (SemanticOperation nestedSemanticAction in nestedSemanticActions)
                        {
                            HandleSemanticOperation(nestedSemanticAction, parser, infoCollector);
                        }

                        if (requestWaiting)
                        {
                            break;
                        }

                        // at the end of each iteration clear flags so that we can do the next iteration
                        operation.SetNestedOperationState("state", SemanticOperation.INIT);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.StackTrace);
                throw new ForLoopException(e, operation, semanticOperationVariableMap);
            }
        }