Ejemplo n.º 1
0
        // GET: Validate
        public ActionResult Index()
        {
            Common.RequestRecord rr = new RequestRecord();
            rr.SaveRequestStr2Log(HttpContext.Request.QueryString.ToString());

            string token        = "lyytoken";
            string signatureStr = HttpContext.Request.QueryString["signature"];
            string timestampStr = HttpContext.Request.QueryString["timestamp"];
            string nonceStr     = HttpContext.Request.QueryString["nonce"];
            string echostr      = HttpContext.Request.QueryString["echostr"];

            BLL.Validate validate = new BLL.Validate();

            ContentResult cr = new ContentResult();

            if (signatureStr is null)
            {
                return(Content("Empty Request"));
            }
            if (validate.checkSignature(signatureStr, timestampStr, nonceStr, token))
            {
                cr.Content = echostr;
                return(cr);
            }
            else
            {
                cr.Content = "ValidateFail";
                return(cr);
            }
        }
Ejemplo n.º 2
0
        public IHttpActionResult DocumentCallBack([FromBody] CallBackResponse request)
        {
            IRequestRecordLog requestRecordLog = new RequestRecordLog();

            actionDocument = new Document();

            try
            {
                RequestRecord record = new RequestRecord()
                {
                    clave             = request.clave,
                    docDatetime       = DateTime.Parse(request.fecha),
                    indState          = request.indEstado,
                    responseXML       = request.respuestaXml,
                    callBacakDatetime = DateTime.Now
                };

                requestRecordLog.UpdateRequestRecord(record);
                //actionDocument.StoreCallBackResponse(request);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                LogManager.RegisterCallBackFailToDataBase(JsonConvert.SerializeObject(request));
            }

            return(Ok());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Adds a request for a particular stock to the database.
        /// </summary>
        /// <param name="stock">
        /// Stock info such as price and phone number to message.
        /// </param>
        /// <returns>
        /// True if adding the request was successful, otherwise false.
        /// </returns>
        public bool AddRequest(Stock stock)
        {
            bool success = true;

            try
            {
                if (limit.IsOverLimit(stock.Phone))
                {
                    return(false);
                }

                var request = new RequestRecord
                {
                    RequestId     = stock.RequestId,
                    Price         = stock.Price,
                    TwilioBinding = Guid.NewGuid().ToString()
                };

                twilio.BindUser(request.TwilioBinding, stock.Phone);

                context.Requests.Add(request);
                limit.Increment(stock.Phone);
                context.SaveChanges();
            }
            catch (DbUpdateException dbException)
            {
                var exception = (Npgsql.PostgresException)dbException.InnerException;
                Console.WriteLine(exception.SqlState);
                success = false;
            }
            return(success);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get the Folder ID for the record
        /// </summary>
        /// <param name="req">Request record</param>
        /// <returns>Guid of the folder, or Guid.Empty if not found</returns>
        public static Guid GetFolderID(RequestRecord req)
        {
            switch (req.ReqType)
            {
            case RequestQueue.RequestRecord.RequestType.Delete:
            case RequestQueue.RequestRecord.RequestType.Insert:
                switch (req.BodyTypeName)
                {
                case "Item":
                    return(((Item)req.Body).FolderID);

                case "Folder":
                    return(((Folder)req.Body).ID);

                default:
                    return(Guid.Empty);
                }

            case RequestQueue.RequestRecord.RequestType.Update:
                switch (req.BodyTypeName)
                {
                case "Item":
                    return(((List <Item>)req.Body)[0].FolderID);

                case "Folder":
                    return(((List <Folder>)req.Body)[0].ID);

                default:
                    return(Guid.Empty);
                }

            default:
                return(Guid.Empty);
            }
        }
Ejemplo n.º 5
0
        public void UpdateRequestRecord(RequestRecord requestRecord)
        {
            RequestRecord record;

            try
            {
                using (DigitalInvoiceEntities context = new DigitalInvoiceEntities())
                {
                    record = (from rr in context.RequestRecord
                              where rr.clave.Equals(requestRecord.clave) && rr.callBackReceived == false
                              select rr).FirstOrDefault();

                    if (record != null)
                    {
                        record.docDatetime       = requestRecord.docDatetime;
                        record.indState          = requestRecord.indState;
                        record.responseXML       = requestRecord.responseXML;
                        record.callBacakDatetime = requestRecord.callBacakDatetime;
                        record.callBackReceived  = true;
                        context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 6
0
        private void ButtonAddTaskClick(object sender, EventArgs e)
        {
            DirectivePackageBindTaskFormNew form = new DirectivePackageBindTaskFormNew(_currentDirective);

            if (form.ShowDialog() == DialogResult.OK)
            {
                foreach (IDirective obj in form.SelectedItems.OfType <IDirective>())
                {
                    RequestRecord newRecord = new RequestRecord
                    {
                        ParentId        = _currentDirective.ItemId,
                        DirectiveId     = obj.ItemId,
                        PackageItemType = obj.SmartCoreObjectType,
                        Task            = obj,
                        ParentPackage   = _currentDirective
                    };
                    _currentDirective.PackageRecords.Add(newRecord);
                }
                IEnumerable <IDirective> directives =
                    _currentDirective.PackageRecords.Where(pr => pr.Task != null).Select(pr => pr.Task).ToArray();
                workOrderViewControl.SetItemsArray(directives.Select(pr => pr as BaseEntityObject));
                numericUpDownMan.Value      = directives.OfType <IEngineeringDirective>().Sum(d => d.Mans);
                numericUpDownManHours.Value = (Decimal)directives.OfType <IEngineeringDirective>().Sum(d => d.ManHours);
                numericUpDownCost.Value     = (Decimal)directives.OfType <IEngineeringDirective>().Sum(d => d.Cost);
            }
        }
Ejemplo n.º 7
0
        public void CanAddRequestRecord()
        {
            ComposerEngine sut = m_ComposerMock.Object;

            RequestRecord testRecord = new RequestRecord();

            sut.AddRequestRecord(testRecord);

            m_RequestRecordsMock.Verify(rr => rr.Add(testRecord));
        }
Ejemplo n.º 8
0
 // deep-copy the passed in newRecord
 public void Copy(RequestRecord record)
 {
     // copy all of the properties
     foreach (PropertyInfo pi in record.GetType().GetProperties())
     {
         // get the value of the property
         var val = pi.GetValue(record, null);
         pi.SetValue(this, val, null);
     }
 }
Ejemplo n.º 9
0
        public void TestRequestRecordTimeStampSet()
        {
            ComposerEngine sut = m_ComposerMock.Object;

            RequestRecord testRecord = new RequestRecord();

            sut.AddRequestRecord(testRecord);

            Assert.NotNull(testRecord.DateCreated);
            Assert.NotNull(testRecord.DateModified);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Enqueue a Web Service record into the record queue
        /// </summary>
        public static void EnqueueRequestRecord(string queueName, RequestRecord newRecord)
        {
            bool enableQueueOptimization = false;  // turn off the queue optimization (doesn't work with introduction of tags)

            List <RequestRecord>       requests = new List <RequestRecord>();
            DataContractJsonSerializer dc       = new DataContractJsonSerializer(requests.GetType());

            if (newRecord.SerializedBody == null)
            {
                newRecord.SerializeBody();
            }

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                lock (fileLocks[queueName])
                {
                    // if the file opens, read the contents
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(QueueFilename(queueName), FileMode.OpenOrCreate, file))
                    {
                        try
                        {
                            // if the file opened, read the record queue
                            requests = dc.ReadObject(stream) as List <RequestRecord>;
                            if (requests == null)
                            {
                                requests = new List <RequestRecord>();
                            }
                        }
                        catch (Exception ex)
                        {
                            stream.Position = 0;
                            string s = new StreamReader(stream).ReadToEnd();
                            TraceHelper.AddMessage(String.Format("Exception in deserializing RequestRQueue: {0}; record: {1}", ex.Message, s));
                        }

                        if (enableQueueOptimization == true)
                        {
                            OptimizeQueue(newRecord, requests);
                        }
                        else
                        {
                            // this is a new record so add the new record at the end
                            requests.Add(newRecord);
                        }

                        // reset the stream and write the new record queue back to the file
                        stream.SetLength(0);
                        stream.Position = 0;
                        dc.WriteObject(stream, requests);
                        stream.Flush();
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public void DidDataEngineManagerSaveRequestRecord()
        {
            var dataAccessMock = new Mock <IDataAccess>();
            var dataEngineMock = new Mock <IDataEngine>();

            DataEngineManager sut = new DataEngineManager(dataAccessMock.Object);

            sut.AddEngine(dataEngineMock.Object);

            RequestRecord testRecord = new RequestRecord();

            dataEngineMock.Raise(de => de.OnNewRequestRecord += null, this, new NewRequestRecordEventArgs(testRecord));

            dataAccessMock.Verify(da => da.AddRequestRecord(testRecord));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Helper method to optimize the queue
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="requests"></param>
        private static void OptimizeQueue(RequestRecord newRecord, List <RequestRecord> requests)
        {
            // try to find a record for the same entity by the local ID
            try
            {
                var existingRecord = requests.Single(r => r.ID == newRecord.ID);
                existingRecord.DeserializeBody();
                UpdateExistingRecord(requests, existingRecord, newRecord);
            }
            catch (Exception)
            {
                // this is a new record so add the new record at the end
                requests.Add(newRecord);
            }

            // if this is a request to remove a folder, need to also remove all the manipulations to items inside that folder
            if (newRecord.ReqType == RequestRecord.RequestType.Delete &&
                newRecord.BodyTypeName == "Folder")
            {
                // create a folder that holds the item references to delete
                List <RequestRecord> deleteList = new List <RequestRecord>();
                // deserialize the bodies for all the items (need FolderID for all the items)
                foreach (var r in requests)
                {
                    if (r.BodyTypeName == "Item")
                    {
                        r.DeserializeBody();
                        Item t;
                        if (r.ReqType == RequestRecord.RequestType.Update)
                        {
                            t = ((List <Item>)r.Body)[0];
                        }
                        else
                        {
                            t = (Item)r.Body;
                        }
                        if (t.FolderID == newRecord.ID)
                        {
                            deleteList.Add(r);
                        }
                    }
                }
                foreach (var r in deleteList)
                {
                    requests.Remove(r);
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Get the first RequestRecord in the queue
        /// </summary>
        public static RequestRecord GetRequestRecord(string queueName)
        {
            List <RequestRecord>       requests = new List <RequestRecord>();
            DataContractJsonSerializer dc       = new DataContractJsonSerializer(requests.GetType());

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                lock (fileLocks[queueName])
                {
                    // try block because the using block below will throw if the file doesn't exist
                    try
                    {
                        // if the file opens, read the contents
                        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(QueueFilename(queueName), FileMode.Open, file))
                        {
                            try
                            {
                                // if the file opens, read the contents
                                requests = dc.ReadObject(stream) as List <RequestRecord>;
                                if (requests.Count > 0)
                                {
                                    RequestRecord record = requests[0];
                                    record.DeserializeBody();
                                    return(record);
                                }
                                else
                                {
                                    return(null);
                                }
                            }
                            catch (Exception ex)
                            {
                                stream.Position = 0;
                                string s = new StreamReader(stream).ReadToEnd();
                                TraceHelper.AddMessage(String.Format("Exception in deserializing RequestRecord: {0}; record: {1}", ex.Message, s));
                                return(null);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // could not open the isolated storage file
                        return(null);
                    }
                }
            }
        }
Ejemplo n.º 14
0
            public void GetData(RequestRecord requestRecord)
            {
                Console.WriteLine("GetData called");
                switch (requestRecord.AssetType)
                {
                case AssetType.Bond:
                    BondServer.GetData(_bondFuture);
                    break;

                case AssetType.Future:
                    FutureServer.GetData(_futureProxy);
                    break;

                default:
                    break;
                }
            }
Ejemplo n.º 15
0
        private static void StoreRequestInformation(HttpContext context,
                                                    string key,
                                                    ConcurrentDictionary <string, ConcurrentQueue <IRequestRecord <object> > > lastRequests)
        {
            object requestObject;

            try
            {
                requestObject = JsonConvert.DeserializeObject(new StreamReader(context.Request.Body).ReadToEnd());
            }
            catch (Exception e)
            {
                logger.LogInformation(new EventId(1234),
                                      e,
                                      "Non-fatal error on deserializing request as json. Request will be stored as a string instead.");
                context.Request.Body.Seek(0, SeekOrigin.Begin);
                requestObject = new StreamReader(context.Request.Body).ReadToEnd();
            }

            var requestHeaders = context.Request.Headers.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());

            var requestParameters = context.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());

            var requestRecord = new RequestRecord <object>
            {
                RequestBody       = requestObject,
                RequestHeaders    = requestHeaders,
                RequestParameters = requestParameters
            };

            lastRequests.AddOrUpdate(key,
                                     (k) =>
            {
                var queue = new ConcurrentQueue <IRequestRecord <object> >();
                queue.Enqueue(requestRecord);
                return(queue);
            },
                                     (s, d) =>
            {
                d.Enqueue(requestRecord);
                return(d);
            }
                                     );
        }
Ejemplo n.º 16
0
        //============================================================================
        /// <summary>
        /// Tracks the requests made to the rest of the system.
        /// </summary>
        /// <param name="eventID">Event ID.</param>
        /// <param name="msgID">Message ID.</param>
        //============================================================================
        public void addRequest(int eventID, uint msgID)
        {
            RequestRecord request;
            int           eventIndex;

            request         = new RequestRecord();
            request.eventID = eventID;
            request.msgID   = msgID;
            requestList.Add(request);

            //add the msgID to the request list of the event
            eventIndex = eventIdx(eventID);
            if (eventIndex >= 0)
            {
                TMEvent anEvent = (TMEvent)eventList[eventIndex];
                anEvent.addRequest(msgID);
                eventList[eventIndex] = anEvent;
            }
        }
Ejemplo n.º 17
0
        public void LogDuplicates(List <string> tableNames, string FunctionName, string operation, string fileName)
        {
            using (StreamWriter file =
                       new StreamWriter(@"logs.txt"))
            {
                foreach (var table in tableNames)
                {
                    var record = RequestRecordsDupl.Where(r => r.FunctionName == FunctionName & r.TableName == table).FirstOrDefault();

                    if (record != null)
                    {
                        if (!record.Operation.Contains(operation))
                        {
                            record.Operation.Add(operation);
                            if (operation != ParsingConstants.SelectString)
                            {
                                record.OperationLevel = 2;
                            }
                        }

                        record.Count++;
                        file.WriteLine("Table {0} : , Function : {1} , Operation : {2} , FileName : {3} ", record.TableName, record.FunctionName, record.Operation, record.File);

                        file.WriteLine("Table {0} : , Function : {1} , Operation : {2} , FileName : {3} ", table, FunctionName, operation, fileName);
                    }
                    else
                    {
                        RequestRecord recordreq = new RequestRecord
                        {
                            FunctionName = FunctionName,
                            Operation    = new List <string> {
                                operation
                            },
                            TableName      = table,
                            Count          = 1,
                            OperationLevel = operation == ParsingConstants.SelectString ? 1 : 2,
                            File           = fileName
                        };
                        RequestRecordsDupl.Add(recordreq);
                    }
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Dequeue the first record
        /// </summary>
        public static RequestRecord DequeueRequestRecord(string queueName)
        {
            List <RequestRecord>       requests = new List <RequestRecord>();
            DataContractJsonSerializer dc       = new DataContractJsonSerializer(requests.GetType());

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                lock (fileLocks[queueName])
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(QueueFilename(queueName), FileMode.Open, file))
                    {
                        try
                        {
                            // if the file opens, read the contents
                            requests = dc.ReadObject(stream) as List <RequestRecord>;
                            if (requests.Count > 0)
                            {
                                RequestRecord record = requests[0];
                                requests.Remove(record);  // remove the first entry
                                stream.SetLength(0);
                                stream.Position = 0;
                                dc.WriteObject(stream, requests);

                                record.DeserializeBody();
                                return(record);
                            }
                            else
                            {
                                return(null);
                            }
                        }
                        catch (Exception ex)
                        {
                            stream.Position = 0;
                            string s = new StreamReader(stream).ReadToEnd();
                            TraceHelper.AddMessage(String.Format("Exception in deserializing RequestRecord: {0}; record: {1}", ex.Message, s));
                            return(null);
                        }
                    }
                }
            }
        }
    public async Task Handle(LongProcessingRequest message, IMessageHandlerContext context)
    {
        log.Info($"Received LongProcessingRequest with ID {message.Id}, EstimatedProcessingTime: {message.EstimatedProcessingTime}.");

        #region setting-timeout

        var timeoutToBeInvokedAt = DateTime.Now + message.EstimatedProcessingTime + TimeSpan.FromSeconds(10);
        var timeoutMessage       = new ProcessingPossiblyFailed
        {
            Id = message.Id
        };
        await RequestTimeout(context, timeoutToBeInvokedAt, timeoutMessage)
        .ConfigureAwait(false);

        #endregion

        log.Info($"Timeout is set to be executed at {timeoutToBeInvokedAt}.");

        log.Info("Registering long running request with Processor.");

        #region enqueue-request-for-processor

        // Saga enqueues the request to process in a storage table. This is the
        // logical equivalent of adding a message to a queue. If there would be
        // business specific work to perform here, that work should be done by
        // sending a message to a handler instead and not handled in the saga.

        var request = new RequestRecord(message.Id, Status.Pending, message.EstimatedProcessingTime);
        await table.ExecuteAsync(TableOperation.Insert(request))
        .ConfigureAwait(false);

        var processingReply = new LongProcessingReply
        {
            Id = message.Id
        };
        await context.Reply(processingReply)
        .ConfigureAwait(false);

        #endregion

        log.Info($"Acknowledged LongProcessingRequest with ID {message.Id}.");
    }
Ejemplo n.º 20
0
        protected override async void Run(Session session, C2G_QueryUserRequestRecord message, Action <G2C_QueryUserRequestRecord> reply)
        {
            G2C_QueryUserRequestRecord response          = new G2C_QueryUserRequestRecord();
            UserRequestRecord          UserRequestRecord = null;

            try
            {
                DBProxyComponent dBProxyComponent = Game.Scene.GetComponent <DBProxyComponent>();

                var acounts = await dBProxyComponent.Query <UserRequestRecord>("{ '_AccountID': " + message.AccountID + "}");

                if (acounts.Count > 0)
                {
                    for (int i = 0; i < acounts.Count; i++)
                    {
                        UserRequestRecord = acounts[i] as UserRequestRecord;

                        RequestRecord record = new RequestRecord();
                        record.AccountID         = UserRequestRecord._AccountID;
                        record.InfoID            = UserRequestRecord._InfoID;
                        record.RequestTimes      = UserRequestRecord._RequestTimes;
                        record.IP                = UserRequestRecord._IP;
                        record.RequestInfo       = UserRequestRecord._RequestInfo;
                        record.RequestTypeCode   = UserRequestRecord._RequestTypeCode;
                        record.RequestResultCode = UserRequestRecord._RequestResultCode;
                        response.Userlist.Add(record);
                    }
                }

                await dBProxyComponent.Save(UserRequestRecord);

                await dBProxyComponent.SaveLog(UserRequestRecord);

                reply(response);
            }
            catch (Exception e)
            {
                response.Message = "数据库异常";
                ReplyError(response, e, reply);
            }
        }
Ejemplo n.º 21
0
 // The constructor is not called by the deserialization mechanism,
 // therefore this is the right place to specify the array size and to
 // perform the array initialization.
 public RequestArray(int totalRecords)
 {
     if (totalRecords > 0 && totalRecords <= 100)
     {
         m_TotalRecords = totalRecords;
         m_Record       = new RequestRecord[totalRecords];
         for (int i = 0; i < m_TotalRecords; i++)
         {
             m_Record[i] = new RequestRecord()
             {
                 Name = "Record #" + i.ToString()
             }
         }
         ;
         m_TotalRecords = totalRecords;
     }
     else
     {
         m_TotalRecords = 0;
     }
 }
Ejemplo n.º 22
0
        //============================================================================
        /// <summary>
        /// Informs the event that sent the msgID, that a return has occured. The
        /// number of remaining requests required by the event is checked. If no returns
        /// are still pending then the event is resumed.
        /// </summary>
        /// <param name="msgID">Message ID.</param>
        //============================================================================
        public void completeRequest(uint msgID)
        {
            int  anEventIdx;
            bool found;
            int  remainingRequests;

            //scan through the request list and find the event that triggered it
            int i = 0;

            found = false;
            while ((!found) && (i < requestList.Count))
            {
                RequestRecord request = (RequestRecord)requestList[i];
                if (request.msgID == msgID)
                {                                           //if the msg request if found
                    found      = true;
                    anEventIdx = eventIdx(request.eventID); //get the TMEvent belonging to the request
                    if (anEventIdx >= 0)
                    {
                        TMEvent anEvent = (TMEvent)eventList[anEventIdx];

                        //now delete the request from the the Event Manager's requestList
                        requestList.RemoveAt(i);
                        remainingRequests = anEvent.completeRequest(msgID); //tell the event that the request is complete
                        if (remainingRequests < 1)                          //if there are no pending requests then
                        {
                            //event.resumeEvent;                                    //resume the event
                            anEvent.setWaiting(false);
                        }
                        eventList[anEventIdx] = anEvent;
                    }
                }
                else
                {
                    i++;   //next event
                }
            }
        }
Ejemplo n.º 23
0
        public void RegisterRequestRecord(string clave, string accountId, string state)
        {
            try
            {
                RequestRecord newRecord = new RequestRecord()
                {
                    clave        = clave,
                    accountId    = accountId,
                    requestState = state,
                    sentDatetime = DateTime.Now
                };

                using (DigitalInvoiceEntities context = new DigitalInvoiceEntities())
                {
                    context.RequestRecord.Add(newRecord);
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
Ejemplo n.º 24
0
 // deep-copy the passed in newRecord
 public void Copy(RequestRecord record)
 {
     // copy all of the properties
     foreach (PropertyInfo pi in record.GetType().GetProperties())
     {
         // get the value of the property
         var val = pi.GetValue(record, null);
         pi.SetValue(this, val, null);
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Helper method to update an existing queue record with new information
        /// </summary>
        /// <param name="requests"></param>
        /// <param name="existingRecord"></param>
        /// <param name="newRecord"></param>
        /// <returns>Whether an update was performed</returns>
        private static bool UpdateExistingRecord(List <RequestRecord> requests, RequestRecord existingRecord, RequestRecord newRecord)
        {
            switch (existingRecord.ReqType)
            {
            case RequestRecord.RequestType.Delete:
                // the existing record in the queue is a delete - this situation can't happen unless there is local corruption (but not necessarily queue corruption)
                // there can be no further action
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    throw new Exception("trying to do something to an already deleted entry");
                }
                return(false);

            case RequestRecord.RequestType.Insert:
                // the existing record in the queue is an insert
                switch (newRecord.ReqType)
                {
                case RequestRecord.RequestType.Delete:
                    // the entity was created and deleted while offline
                    // the existing record needs to be removed
                    requests.Remove(existingRecord);
                    return(true);

                case RequestRecord.RequestType.Insert:
                    // this doesn't make sense because it violates the Guid uniqueness principle
                    // since the record already exists, we're not going to insert a new one - take no action
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        throw new Exception("insert after an insert");
                    }
                    return(false);

                case RequestRecord.RequestType.Update:
                    // an update on top of an insert
                    // replace the new value in the existing insert record with the "new" value in the update
                    switch (existingRecord.BodyTypeName)
                    {
                    case "Tag":
                        List <Tag> newRecordTagList = (List <Tag>)newRecord.Body;
                        existingRecord.Body = newRecordTagList[1];
                        break;

                    case "Item":
                        List <Item> newRecordFolder = (List <Item>)newRecord.Body;
                        existingRecord.Body = newRecordFolder[1];
                        break;

                    case "Folder":
                        List <Folder> newRecordFolderList = (List <Folder>)newRecord.Body;
                        existingRecord.Body = newRecordFolderList[1];
                        break;
                    }
                    // reserialize the body
                    existingRecord.SerializeBody();
                    return(true);
                }
                break;

            case RequestRecord.RequestType.Update:
                // the existing record in the queue is an update
                switch (newRecord.ReqType)
                {
                case RequestRecord.RequestType.Delete:
                    // the entity was updated and now deleted while offline
                    // the existing record needs to be amended to a delete record
                    existingRecord.Copy(newRecord);
                    return(true);

                case RequestRecord.RequestType.Insert:
                    // this doesn't make sense because it violates the Guid uniqueness principle
                    // since the record already exists, we're not going to insert a new one - take no action
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        throw new Exception("insert after an update");
                    }
                    return(false);

                case RequestRecord.RequestType.Update:
                    // an update on top of an update
                    // replace the new value in the existing record with the "new" new value
                    switch (existingRecord.BodyTypeName)
                    {
                    case "Tag":
                        List <Tag> existingRecordTagList = (List <Tag>)existingRecord.Body;
                        List <Tag> newRecordTagList      = (List <Tag>)newRecord.Body;
                        existingRecordTagList[1] = newRecordTagList[1];
                        break;

                    case "Item":
                        List <Item> existingRecordFolder = (List <Item>)existingRecord.Body;
                        List <Item> newRecordFolder      = (List <Item>)newRecord.Body;
                        existingRecordFolder[1] = newRecordFolder[1];
                        break;

                    case "Folder":
                        List <Folder> existingRecordFolderList = (List <Folder>)existingRecord.Body;
                        List <Folder> newRecordFolderList      = (List <Folder>)newRecord.Body;
                        existingRecordFolderList[1] = newRecordFolderList[1];
                        break;
                    }
                    // reserialize the body
                    existingRecord.SerializeBody();
                    return(true);
                }
                break;
            }

            // no case was triggered - this is an exceptional situation
            if (System.Diagnostics.Debugger.IsAttached)
            {
                throw new Exception("queue corrupted");
            }

            return(false);
        }
Ejemplo n.º 26
0
 public NewRequestRecordEventArgs(RequestRecord requestRecord)
 {
     m_RequestRecord = requestRecord;
 }
Ejemplo n.º 27
0
        public void FindFunctionCalls(string fileName, string file)
        {
            string currentFile = file;

            while (currentFile.Contains("Call"))
            {
                int indexOfCall        = currentFile.IndexOf("Call");
                var indexOfFunctionEnd = currentFile.IndexOf("(", indexOfCall);

                var FunctionCallString   = currentFile.Substring(indexOfCall, indexOfFunctionEnd - indexOfCall);
                var FunctionCallStringAr = FunctionCallString.Split(" ");

                if (FunctionCallStringAr.Count() > 1)
                {
                    string FunctionCalled = FunctionCallStringAr[1];

                    if (FunctionsNamesList.Contains(FunctionCalled.ToLower()))
                    {
                        string functionFullText = "";

                        CutFileOnCurrentFunctionAndRest(ref currentFile, FunctionCallString,
                                                        ref functionFullText);

                        //Get function name
                        //when the rest of the file does not have the function anymore ? but how could that be...
                        string FunctionName = "";

                        if (!functionFullText.ToLower().Contains("function:"))
                        {
                            FunctionName = FileName.ToLower();
                        }
                        else
                        {
                            FunctionName = GetFunctionName(functionFullText);
                        }

                        var record = RequestRecords.Where(r => r.FunctionName == FunctionCalled & r.CalledByFunction == FunctionName)
                                     .FirstOrDefault();


                        if (record == null)
                        {
                            RequestRecord recordreq = new RequestRecord
                            {
                                FunctionName = FunctionCalled,
                                Operation    = new List <string> {
                                    "FunctionCall"
                                },
                                CalledByFunction = FunctionName,
                                Count            = 1,
                                OperationLevel   = 1
                            };

                            RequestRecords.Add(recordreq);
                        }
                    }
                    else
                    {
                        currentFile = currentFile.Substring(indexOfFunctionEnd);
                    }
                }
                else
                {
                    currentFile = currentFile.Substring(indexOfFunctionEnd);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Helper method to optimize the queue
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="requests"></param>
        private static void OptimizeQueue(RequestRecord newRecord, List<RequestRecord> requests)
        {
            // try to find a record for the same entity by the local ID
            try
            {
                var existingRecord = requests.Single(r => r.ID == newRecord.ID);
                existingRecord.DeserializeBody();
                UpdateExistingRecord(requests, existingRecord, newRecord);
            }
            catch (Exception)
            {
                // this is a new record so add the new record at the end
                requests.Add(newRecord);
            }

            // if this is a request to remove a tasklist, need to also remove all the manipulations to tasks inside that list
            if (newRecord.ReqType == RequestRecord.RequestType.Delete &&
                newRecord.BodyTypeName == "TaskList")
            {
                // create a list that holds the task references to delete
                List<RequestRecord> deleteList = new List<RequestRecord>();
                // deserialize the bodies for all the tasks (need TaskListID for all the tasks)
                foreach (var r in requests)
                {
                    if (r.BodyTypeName == "Task")
                    {
                        r.DeserializeBody();
                        Task t;
                        if (r.ReqType == RequestRecord.RequestType.Update)
                            t = ((List<Task>)r.Body)[0];
                        else
                            t = (Task)r.Body;
                        if (t.TaskListID == newRecord.ID)
                            deleteList.Add(r);
                    }
                }
                foreach (var r in deleteList)
                    requests.Remove(r);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Helper method to update an existing queue record with new information
        /// </summary>
        /// <param name="requests"></param>
        /// <param name="existingRecord"></param>
        /// <param name="newRecord"></param>
        /// <returns>Whether an update was performed</returns>
        private static bool UpdateExistingRecord(List<RequestRecord> requests, RequestRecord existingRecord, RequestRecord newRecord)
        {
            switch (existingRecord.ReqType)
            {
                case RequestRecord.RequestType.Delete:
                    // the existing record in the queue is a delete - this situation can't happen unless there is local corruption (but not necessarily queue corruption)
                    // there can be no further action
                    if (System.Diagnostics.Debugger.IsAttached)
                        throw new Exception("trying to do something to an already deleted entry");
                    return false;
                case RequestRecord.RequestType.Insert:
                    // the existing record in the queue is an insert
                    switch (newRecord.ReqType)
                    {
                        case RequestRecord.RequestType.Delete:
                            // the entity was created and deleted while offline
                            // the existing record needs to be removed
                            requests.Remove(existingRecord);
                            return true;
                        case RequestRecord.RequestType.Insert:
                            // this doesn't make sense because it violates the Guid uniqueness principle
                            // since the record already exists, we're not going to insert a new one - take no action
                            if (System.Diagnostics.Debugger.IsAttached)
                                throw new Exception("insert after an insert");
                            return false;
                        case RequestRecord.RequestType.Update:
                            // an update on top of an insert
                            // replace the new value in the existing insert record with the "new" value in the update
                            switch (existingRecord.BodyTypeName)
                            {
                                case "Tag":
                                    List<Tag> newRecordTagList = (List<Tag>)newRecord.Body;
                                    existingRecord.Body = newRecordTagList[1];
                                    break;
                                case "Task":
                                    List<Task> newRecordTaskList = (List<Task>)newRecord.Body;
                                    existingRecord.Body = newRecordTaskList[1];
                                    break;
                                case "TaskList":
                                    List<TaskList> newRecordTaskListList = (List<TaskList>)newRecord.Body;
                                    existingRecord.Body = newRecordTaskListList[1];
                                    break;
                            }
                            // reserialize the body
                            existingRecord.SerializeBody();
                            return true;
                    }
                    break;
                case RequestRecord.RequestType.Update:
                    // the existing record in the queue is an update
                    switch (newRecord.ReqType)
                    {
                        case RequestRecord.RequestType.Delete:
                            // the entity was updated and now deleted while offline
                            // the existing record needs to be amended to a delete record
                            existingRecord.Copy(newRecord);
                            return true;
                        case RequestRecord.RequestType.Insert:
                            // this doesn't make sense because it violates the Guid uniqueness principle
                            // since the record already exists, we're not going to insert a new one - take no action
                            if (System.Diagnostics.Debugger.IsAttached)
                                throw new Exception("insert after an update");
                            return false;
                        case RequestRecord.RequestType.Update:
                            // an update on top of an update
                            // replace the new value in the existing record with the "new" new value
                            switch (existingRecord.BodyTypeName)
                            {
                                case "Tag":
                                    List<Tag> existingRecordTagList = (List<Tag>)existingRecord.Body;
                                    List<Tag> newRecordTagList = (List<Tag>)newRecord.Body;
                                    existingRecordTagList[1] = newRecordTagList[1];
                                    break;
                                case "Task":
                                    List<Task> existingRecordTaskList = (List<Task>)existingRecord.Body;
                                    List<Task> newRecordTaskList = (List<Task>)newRecord.Body;
                                    existingRecordTaskList[1] = newRecordTaskList[1];
                                    break;
                                case "TaskList":
                                    List<TaskList> existingRecordTaskListList = (List<TaskList>)existingRecord.Body;
                                    List<TaskList> newRecordTaskListList = (List<TaskList>)newRecord.Body;
                                    existingRecordTaskListList[1] = newRecordTaskListList[1];
                                    break;
                            }
                            // reserialize the body
                            existingRecord.SerializeBody();
                            return true;
                    }
                    break;
            }

            // no case was triggered - this is an exceptional situation
            if (System.Diagnostics.Debugger.IsAttached)
                throw new Exception("queue corrupted");

            return false;
        }
Ejemplo n.º 30
0
 public void AddRequestRecord(RequestRecord requestRecord)
 {
     AddTimestampsToEntity(RequestRecords.Add(requestRecord));
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Enqueue a Web Service record into the record queue
        /// </summary>
        public static void EnqueueRequestRecord(RequestRecord newRecord)
        {
            bool enableQueueOptimization = false;  // turn off the queue optimization (doesn't work with introduction of tags)

            List<RequestRecord> requests = new List<RequestRecord>();
            DataContractJsonSerializer dc = new DataContractJsonSerializer(requests.GetType());

            if (newRecord.SerializedBody == null)
                newRecord.SerializeBody();

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                lock (fileLock)
                {
                    // if the file opens, read the contents
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"RequestRecords.xml", FileMode.OpenOrCreate, file))
                    {
                        try
                        {
                            // if the file opened, read the record queue
                            requests = dc.ReadObject(stream) as List<RequestRecord>;
                            if (requests == null)
                                requests = new List<RequestRecord>();
                        }
                        catch (Exception)
                        {
                            stream.Position = 0;
                            string s = new StreamReader(stream).ReadToEnd();
                        }

                        if (enableQueueOptimization == true)
                        {
                            OptimizeQueue(newRecord, requests);
                        }
                        else
                        {
                            // this is a new record so add the new record at the end
                            requests.Add(newRecord);
                        }

                        // reset the stream and write the new record queue back to the file
                        stream.SetLength(0);
                        stream.Position = 0;
                        dc.WriteObject(stream, requests);
                        stream.Flush();
                    }
                }
            }
        }
Ejemplo n.º 32
0
        public void FindTableOperations(string operation, string file)
        {
            //if we see the insert statement, we can drop everything after and finf the last function in the file

            string currentFile = file;

            while (currentFile.Contains(operation))
            {
                string functionFullText = "";

                CutFileOnCurrentFunctionAndRest(ref currentFile, operation,
                                                ref functionFullText);

                //Get function name
                //when the rest of the file does not have the function anymore ? but how could that be...
                string FunctionName = "";

                if (!functionFullText.ToLower().Contains("function:"))
                {
                    FunctionName = FileName;
                }
                else
                {
                    FunctionName = GetFunctionName(functionFullText);
                }
                //Get all sql operation calls in current function
                List <string> tableNames = GetTableNames(functionFullText, operation);
                LogDuplicates(tableNames, FunctionName, operation, FileName);
                foreach (var table in tableNames)
                {
                    var record = RequestRecords.Where(r => r.FunctionName == FunctionName & r.TableName == table).FirstOrDefault();


                    if (record != null)
                    {
                        if (!record.Operation.Contains(operation))
                        {
                            record.Operation.Add(operation);
                            if (operation != ParsingConstants.SelectString)
                            {
                                record.OperationLevel = 2;
                            }
                        }

                        record.Count++;
                    }
                    else
                    {
                        RequestRecord recordreq = new RequestRecord
                        {
                            FunctionName = FunctionName.ToLower(),
                            Operation    = new List <string> {
                                operation
                            },
                            TableName      = table.ToLower(),
                            Count          = 1,
                            OperationLevel = operation == ParsingConstants.SelectString ? 1 :2
                        };

                        RequestRecords.Add(recordreq);

                        FunctionsNamesList.Add(FunctionName.ToLower());
                    }
                }
            }
        }
Ejemplo n.º 33
0
        internal Instrument GetInstrument(string reqID)
        {
            RequestRecord record = mdRequests[reqID] as RequestRecord;

            return((record == null) ? null : InstrumentManager.Instruments[record.Symbol]);
        }