Esempio n. 1
0
            public void Execute_enumerates_results()
            {
                var handler = new ResultHandler();
                var operation = new Mock<Executor.OperationBase>(handler) { CallBase = true };

                operation.Object.Execute(() => YieldResults());

                Assert.IsType<string[]>(handler.Result);
                Assert.Equal(new[] { "Twilight Sparkle", "Princess Celestia" }, handler.Result);
            }
Esempio n. 2
0
        public void OnResult_works()
        {
            var handler = new ResultHandler();
            var result = "Twilight Sparkle";

            handler.OnResult(result);

            Assert.True(handler.HasResult);
            Assert.Equal(result, handler.Result);
        }
Esempio n. 3
0
            public void Execute_sets_results()
            {
                var handler = new ResultHandler();
                var operation = new Mock<Executor.OperationBase>(handler) { CallBase = true };
                var result = "Twilight Sparkle";

                operation.Object.Execute(() => result);

                Assert.Equal(result, handler.Result);
            }
    public override void Execute(string sql, ResultHandler resultHandler, ErrorHandler errorHandler)
    {
        if (sql == "fix_newlines") {
            FixNewlines(resultHandler, errorHandler);
            return;
        }

        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = sql;
        Execute(cmd, resultHandler, errorHandler);
    }
Esempio n. 5
0
            public void Execute_catches_exceptions()
            {
                var handler = new ResultHandler();
                var operation = new Mock<Executor.OperationBase>(handler) { CallBase = true };
                var error = new ArgumentOutOfRangeException("Needs to be about 20% more cool.");

                operation.Object.Execute(() => { throw error; });

                Assert.Equal(error.GetType().AssemblyQualifiedName, handler.ErrorType);
                Assert.Equal(error.Message, handler.ErrorMessage);
                Assert.NotEmpty(handler.ErrorStackTrace);
            }
Esempio n. 6
0
        public void OnError_works()
        {
            var handler = new ResultHandler();
            var type = "System.ArgumentOutOfRangeException";
            var message = "Needs to be about 20% more cool.";
            var stackTrace = "The Coolest Trace Yet";

            handler.OnError(type, message, stackTrace);

            Assert.Equal(type, handler.ErrorType);
            Assert.Equal(message, handler.ErrorMessage);
            Assert.Equal(stackTrace, handler.ErrorStackTrace);
        }
    public void Execute(SqlCommand cmd, ResultHandler resultHandler, ErrorHandler errorHandler)
    {
        #if DEBUG
        Console.WriteLine("Execute: {0}", Util.SqlCommandToString(cmd));
        #endif
        string result = null;
        DataTable dt = null;
        if ((result = Connect()) != null) {
            if (errorHandler != null) {
                //TODO: Move this into Connect() itself
                errorHandler(result, null);
            }
            return;
        }

        try {
            cmd.Connection = _con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            da.Dispose();
            da = null;
        #if DEBUG
            dt.TableName = "Result";
            using(var writer = new System.IO.StringWriter()) {
                dt.WriteXml(writer);
                Console.WriteLine(writer.ToString());
            }
        #endif
        } catch (Exception e) {
            Console.WriteLine("Exception querying DB: {0}", e.Message);
            if (errorHandler != null) {
                errorHandler(e.Message, e);
            }
        }
        if (resultHandler != null) {
            resultHandler(dt);
        }
    }
Esempio n. 8
0
        public ResultHandler <PaginatedList <StudentWeightDto> > GetList(Guid studentId, Pageable pageable = null)
        {
            ResultHandler <PaginatedList <StudentWeightDto> > resultHandler = new ResultHandler <PaginatedList <StudentWeightDto> >();

            try
            {
                Student student = _studentRepository.FindOne(studentId);
                if (student == null)
                {
                    throw new Exception("No such student exists");
                }

                IEnumerable <StudentWeight> studentWeights = _studentWeightRepository.FindAll(student);
                var studentWeightsPaged = AutoMapper.Mapper.Map <IEnumerable <StudentWeight>, PaginatedList <StudentWeightDto> >(studentWeights);
                resultHandler.Data = PaginatedList <StudentWeightDto> .Create(studentWeightsPaged.AsQueryable(), pageable);
            }
            catch (Exception ex)
            {
                resultHandler.Errors.Add(ex.Message);
            }

            return(resultHandler);
        }
Esempio n. 9
0
        public ResultHandler <StudentWeightDto> Delete(Guid studentWeightId)
        {
            ResultHandler <StudentWeightDto> resultHandler = new ResultHandler <StudentWeightDto>();

            try
            {
                StudentWeight studentWeight = _studentWeightRepository.FindOne(studentWeightId);
                if (studentWeight == null)
                {
                    resultHandler.Errors.Add("No such student weight exists");
                }

                _studentWeightRepository.Delete(studentWeight);

                resultHandler.Data = AutoMapper.Mapper.Map <StudentWeight, StudentWeightDto>(studentWeight);
            }
            catch (Exception ex)
            {
                resultHandler.Errors.Add(ex.Message);
            }

            return(resultHandler);
        }
Esempio n. 10
0
    protected virtual void OnResult(ResultType result)
    {
        if (this.lastResult != null)
        {
            return;
        }
        this.lastResult = new ResultHandler
        {
            alert  = this,
            result = result
        };

        if (this.animationObject != null)
        {
            this.animationObject.Play(PanelAnimationNames.BounceOut);
        }
        else
        {
            this.activeAction?.Invoke(this.lastResult);
            this.activeAction = null;
            this.ToggleActive(false);
        }
        this.PlaySfx();
    }
        public IActionResult Edit(Guid id, [Bind("Id,StudentId,TrainerId,DateTime,Hour,Minutes,IsCompleted", Prefix = "Data")] LessonDto lesson)
        {
            ResultHandler <LessonDto> resultHandler = new ResultHandler <LessonDto>();

            if (id != lesson.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    resultHandler = _lessonService.Update(lesson);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LessonExists(lesson.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StudentId"] = new SelectList(_studentService.GetList().Data, "Id", "LastName");
            ViewData["TrainerId"] = new SelectList(_trainerService.GetList().Data, "Id", "LastName");

            ResultViewModel <LessonDto> lessonViewModel =
                AutoMapper.Mapper.Map <ResultHandler <LessonDto>, ResultViewModel <LessonDto> >(resultHandler);

            return(View(lessonViewModel));
        }
Esempio n. 12
0
        public ResultHandler <LessonDto> Delete(Guid lessonId)
        {
            ResultHandler <LessonDto> resultHandler = new ResultHandler <LessonDto>();

            try
            {
                Lesson lesson = _lessonRepository.FindOne(lessonId);
                if (lesson == null)
                {
                    resultHandler.Errors.Add("No such lesson exists");
                    return(resultHandler);
                }


                _lessonRepository.Delete(lesson);
                resultHandler.Data = AutoMapper.Mapper.Map <Lesson, LessonDto>(lesson);
            }
            catch (Exception ex)
            {
                resultHandler.Errors.Add(ex.Message);
            }

            return(resultHandler);
        }
Esempio n. 13
0
        public void Confirm(string title, string content, ResultHandler handler, ButtonType buttonType, Panel container)
        {
            if (this.Current == null)
            {
                if (container == null)
                {
                    container = m_browser.SelectedContent as Panel;
                }
                PopupBox box = new PopupBox(container, this);
                box.ResultHandler += handler;
                box.Confirm(title, content, handler, buttonType, container);
            }
            else
            {
                if (UtilityHelper.IsNullOrEmpty(title))
                {
                    title = MessageResource.ResourceManager.GetString(string.Format("PopupBox_Title_{0}", Newegg.Oversea.Silverlight.Controls.Components.MessageType.Confirm.ToString()));
                }

                m_buttonType = buttonType;

                Show(content, title, PopType.Confirm, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Confirm);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Executed after the download is finished
        /// </summary>
        /// <param name="data"></param>
        private void LoadCompleteHandler(object data)
        {
            //Debug.Log("LoadCompleteHandler");

            AsyncToken httpToken = (AsyncToken)data;

            string path = (string)httpToken.Data;

            T output = ResponseExtractor(httpToken.Response);

            _finished.Add(path, output);

            _tokenToTokens[httpToken].ForEach(delegate(AsyncToken token)
            {
                token.Response = httpToken.Response;

                if (null != _tokenUpdater)
                {
                    TokenUpdater(token, output);
                }

                /**
                 * Execute callback function
                 * */
                if (_callbacks.ContainsKey(token))
                {
                    ResultHandler resultHandler = _callbacks[token];
                    _callbacks.Remove(token);
                    resultHandler(token);
                }
            });

            _tokenToTokens.Remove(httpToken);

            _active.Remove(path);
        }
Esempio n. 15
0
        public async Task Put_WhenDifferentOwnerId_ShouldReturnUnauthorized()
        {
            //Arrange
            ResultHandler <EventModel> expected = ResultHandler.Ok(this._eventModels.First());

            this._genericServiceMock
            .Setup(x => x.GetById(It.IsAny <Guid>()))
            .ReturnsAsync(expected);

            this._genericServiceMock
            .Setup(x => x.Update(It.IsAny <EventModel>()))
            .ReturnsAsync(ResultHandler.Ok());

            this._userServiceMock
            .Setup(x => x.OwnerId)
            .Returns(Guid.NewGuid());

            //Act
            EventPutRequest eventPutRequest = new EventPutRequest();
            IActionResult   actual          = await this._controller.Update(eventPutRequest);

            //Assert
            AssertHttpCode <UnauthorizedObjectResult>(actual, eventPutRequest.GetHashCode());
        }
Esempio n. 16
0
 public InvokerWrapper(IInvoker invoker, IInvokeFilter[]  filters, ResultHandler resultHandler = null)
 {
     _invoker = invoker;
     _filters = filters;
     _resultHandler = resultHandler ?? SeifApplication.AppEnv.GlobalConfiguration.ConsumerConfiguration.GetResultHandler();
 }
            public override void write(byte[] buffer, int offset, int size,
					 ResultHandler rh)
            {
                mSocket.SendAsync(setupRW(buffer, offset, size, rh, MoSync.Constants.CONNOP_WRITE));
            }
Esempio n. 18
0
 public Responder(ResultHandler resultHandler, FaultHandler faultHandler)
 {
     _resultHandler = resultHandler;
     _faultHandler = faultHandler;
 }
Esempio n. 19
0
        public static async void Show(String text, String caption = null, EMessageBoxButtons buttons = EMessageBoxButtons.Ok, ResultHandler handler = null)
        {
            MessageBox.handler = handler;

            MessageDialog dialog;

            if (caption != null)
            {
                dialog = new MessageDialog(text, caption);
            }
            else
            {
                dialog = new MessageDialog(text);
            }

            // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
            dialog.Commands.Add(new UICommand("ok", new UICommandInvokedHandler(CommandInvokedHandler)));

            if (buttons == EMessageBoxButtons.OkCancel)
            {
                dialog.Commands.Add(new UICommand("cancel", new UICommandInvokedHandler(CommandInvokedHandler)));
            }

            // Show the message dialog
            await dialog.ShowAsync();
        }
Esempio n. 20
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach (KeyValuePair <int, Connection> p in mConnections)
                {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.handle, handle);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.opType, connOp);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maConnect(" + url + ")\n");
                if (url.StartsWith("btspp"))
                {
                    return(MoSync.Constants.CONNERR_UNAVAILABLE);
                }
                Uri        uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return(MoSync.Constants.CONNERR_GENERIC);
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return(mNextConnHandle++);
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                if (_conn == MoSync.Constants.HANDLE_LOCAL)                 // unavailable
                {
                    return(-1);
                }
                Connection c = mConnections[_conn];
                return(c.getAddr(core.GetDataMemory(), _addr));
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                                                 CommDelegate cd)
            {
                Connection c   = mConnections[_conn];
                Resource   res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream     s   = (Stream)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                MemoryStream mem = null;
                if (s.GetType() == typeof(MemoryStream))
                {
                    mem = (MemoryStream)s;
                }
                else
                {
                    MoSync.Util.CriticalError("Only binaries (non-ubins) are allowed for maConn(Read/Write)(To/From)Data");
                }

                cd(c, mem.GetBuffer(),
                   delegate(int handle, int connOp, int result)
                {
                    runtime.SetResourceRaw(_data, res);
                    mResultHandler(handle, connOp, result);
                });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                             delegate(Connection c, byte[] buf, ResultHandler rh)
                {
                    c.recv(buf, _offset, _size, rh);
                });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                             delegate(Connection c, byte[] buf, ResultHandler rh)
                {
                    c.write(buf, _offset, _size, rh);
                });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maHttpCreate(" + url + ")\n");
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return(mNextConnHandle++);
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key             = core.GetDataMemory().ReadStringAtAddress(_key);
                String value           = core.GetDataMemory().ReadStringAtAddress(_value);
                if (value.Length > 0)
                {
                    c.setRequestHeader(key, value);
                }
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key             = core.GetDataMemory().ReadStringAtAddress(_key);
                String value           = c.getResponseHeader(key);
                if (value == null)
                {
                    return(MoSync.Constants.CONNERR_NOHEADER);
                }
                if (value.Length + 1 <= _bufSize)
                {
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                }
                return(value.Length);
            };
        }
 // asynchronous
 public abstract void connect(ResultHandler rh);
Esempio n. 22
0
        public static async void AvatarUpload(String filePath, ResultHandler handler, ErrorHandler errorHandler)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    return;
                }

                Directory.CreateDirectory(TempUtil.RenderTempPath);
                String tempPath = Path.Combine(TempUtil.RenderTempPath, "MyAvatar");

                Image image = Image.FromFile(filePath);
                int   w     = image.Width;
                int   h     = image.Height;

                if (w > h)
                {
                    if (h > 500)
                    {
                        w = 500 * w / h;
                        h = 500;
                    }
                }
                else
                {
                    if (w > 500)
                    {
                        h = 500 * h / w;
                        w = 500;
                    }
                }

                Image thumbnail = image.GetThumbnailImage(w, h, null, IntPtr.Zero);

                HttpClient httpClient = new HttpClient();

                httpClient.DefaultRequestHeaders.Add(ClientSession.HeaderToken, ChatConnection.Instance.Session.SessionID);

                MultipartFormDataContent form = new MultipartFormDataContent();

                thumbnail.Save(tempPath);
                FileStream stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
                form.Add(new StreamContent(stream), "avatar", ChatConnection.Instance.Session.SessionID);

                String address = ChatConnection.Instance.WebHost;
                int    port    = ChatConnection.Instance.WebPort;
                String url     = String.Format(UploadAvatarURL, address, port);

                HttpResponseMessage response = await httpClient.PostAsync(url, form);

                response.EnsureSuccessStatusCode();
                httpClient.Dispose();
                stream.Close();
                stream.Dispose();
                image.Dispose();
                thumbnail.Dispose();
                handler();
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }
            catch (Exception e)
            {
                if (errorHandler != null)
                {
                    errorHandler(e);
                }
            }
        }
Esempio n. 23
0
 public Page Bind(Page page, BaseVM owner, Bridge bridge, ResultHandler handler, ExcelExporter <T> exporter, Directory <T> directory, Validator <T> validator, Filtrator <T> filtrator)
 {
     Exporter = exporter;
     return(Bind(page, owner, bridge, handler, directory, validator, filtrator));
 }
Esempio n. 24
0
 public static extern void chain_organize_transaction(IntPtr chain, IntPtr context, IntPtr transaction, ResultHandler handler);
Esempio n. 25
0
 public abstract void Execute(string sql, ResultHandler resultHandler, ErrorHandler errorHandler);
Esempio n. 26
0
 public ProfilingTimer(ResultHandler resultHandler)
 {
     _stopWatch = Stopwatch.StartNew();
     _resultHandler = resultHandler;
 }
Esempio n. 27
0
    private void FixNewlines(ResultHandler resultHandler, ErrorHandler errorHandler)
    {
        string dbName = "orcad_development_fix_footprints";
        string sql = string.Format("SELECT TABLE_NAME FROM [{0}].information_schema.tables", dbName);
        string finalSql = "";
        Execute(sql, delegate(DataTable tableResult) {
            foreach (DataRow tableRow in tableResult.Rows) {
                string tableName = tableRow["TABLE_NAME"].ToString();
                sql = string.Format(
                    "SELECT COLUMN_NAME FROM [{0}].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{1}' AND COLUMN_NAME = '{2}'",
                    dbName,
                    tableName,
                    "PCB Footprint"
                    );
                Execute(sql, delegate(DataTable columnResult) {
                    if (columnResult.Rows.Count > 0) {
                        sql = string.Format(
                            "SELECT [Part Number], [PCB Footprint] FROM [{0}].[dbo].[{1}] WHERE [PCB Footprint] LIKE '%['+CHAR(10)+CHAR(13)+']%'",
                            dbName,
                            tableName
                            );
                        Execute(sql, delegate(DataTable fpResult) {
                            foreach (DataRow fpRow in fpResult.Rows) {
                                string partNum = fpRow["Part Number"].ToString();
                                string footprint = fpRow["PCB Footprint"].ToString().Replace("\nD3-SM_R_1206", "").Replace("\r", "").Replace("\n", "");
                                string previousValue = fpRow["PCB Footprint"].ToString().Replace("\r", "\\r").Replace("\n", "\\n");
                                sql = string.Format("UPDATE [{0}].[dbo].[{1}] SET [PCB Footprint] = '{2}' WHERE [Part Number] = '{3}'; -- Previous value: {4}",
                                    dbName,
                                    tableName,
                                    footprint,
                                    partNum,
                                    previousValue
                                    );
                                //Execute(sql, null, errorHandler);
                                finalSql += sql + "\r\n";
                            }
                        }, errorHandler);
                    }
                }, errorHandler);
            }
            //foreach (DataRow srcRow in result.Rows) {
                //
            //}
        }, errorHandler);

        errorHandler(finalSql, null);
    }
Esempio n. 28
0
 public async Task <ResultHandler> ConfirmUser(ConfirmUserDto data)
 {
     return(ResultHandler.HandleTaskResult(await repository.ConfirmUser(data)));
 }
 private void AssertException(ResultHandler actual)
 {
     Assert.IsNotNull(actual);
     Assert.IsFalse(actual.Success);
     Assert.AreEqual(this._exception, actual.Exception);
 }
Esempio n. 30
0
 public ActionDoEvent()
 {
     _event = new Handler(onActionDo);
     _resultEvent = new ResultHandler(onActionDoResult);
 }
            public override void connect(ResultHandler rh)
            {
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = mHostEntry;
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(
                    delegate(object s, SocketAsyncEventArgs e)
                {
                    int result;
                    if (e.SocketError == SocketError.Success)
                    {
                        result = 1;
                    }
                    else
                    {
                        result = MoSync.Constants.CONNERR_GENERIC;
                    }
                    rh(mHandle, MoSync.Constants.CONNOP_CONNECT, result);
                });

                mSocket.ConnectAsync(socketEventArg);
            }
Esempio n. 32
0
 private void Broadcast(string string_1, int int_1, byte[] byte_0, string string_2, int int_2, ResultHandler resultHandler_0, object object_0)
 {
     try
     {
         this.BroadcastBlob(string_1, int_1, byte_0, string_2, int_2);
         if (resultHandler_0 != null)
         {
             resultHandler_0(true, object_0);
         }
     }
     catch (Exception)
     {
         if (resultHandler_0 != null)
         {
             resultHandler_0(false, object_0);
         }
     }
 }
Esempio n. 33
0
 // asynchronous
 public abstract void connect(ResultHandler rh);
Esempio n. 34
0
 public void BroadcastBlob(string groupID, int broadcastType, byte[] blobContent, string tag, int fragmentSize, ResultHandler handler, object handlerTag)
 {
     new CbGeneric <string, int, byte[], string, int, ResultHandler, object>(this.Broadcast).BeginInvoke(groupID, broadcastType, blobContent, tag, fragmentSize, handler, handlerTag, null, null);
 }
Esempio n. 35
0
 public abstract void write(byte[] buffer, int offset, int size, ResultHandler rh);
Esempio n. 36
0
 private void method_9(string string_4, int int_2, byte[] byte_0, string string_5, int int_3, ResultHandler resultHandler_0, object object_1)
 {
     try
     {
         this.SendMessage(string_4, int_2, byte_0, string_5, int_3);
         if (resultHandler_0 != null)
         {
             resultHandler_0(true, object_1);
         }
     }
     catch (Exception)
     {
         if (resultHandler_0 != null)
         {
             resultHandler_0(false, object_1);
         }
     }
 }
Esempio n. 37
0
 public Responder(ResultHandler resultHandler)
 {
     _resultHandler = resultHandler;
 }
Esempio n. 38
0
 public void SendMessage(string targetUserID, int informationType, byte[] message, string tag, int fragmentSize, ResultHandler handler, object handlerTag)
 {
     new CbGeneric <string, int, byte[], string, int, ResultHandler, object>(this.method_9).BeginInvoke(targetUserID, informationType, message, tag, fragmentSize, handler, handlerTag, null, null);
 }
            public override void recv(byte[] buffer, int offset, int size,
					 ResultHandler rh)
            {
                mSocket.ReceiveAsync(setupRW(buffer, offset, size, rh, MoSync.Constants.CONNOP_READ));
            }
 public override void write(byte[] buffer, int offset, int size,
      ResultHandler rh)
 {
     mSocket.SendAsync(setupRW(buffer, offset, size, rh));
 }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach (KeyValuePair<int, Connection> p in mConnections)
                {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.handle, handle);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.opType, connOp);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maConnect(" + url + ")\n");
                if (url.StartsWith("btspp"))
                    return MoSync.Constants.CONNERR_UNAVAILABLE;
                Uri uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return MoSync.Constants.CONNERR_GENERIC;
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                if (_conn == MoSync.Constants.HANDLE_LOCAL) // unavailable
                    return -1;
                Connection c = mConnections[_conn];
                return c.getAddr(core.GetDataMemory(), _addr);
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                    CommDelegate cd)
            {
                Connection c = mConnections[_conn];
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream s = (Stream)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                MemoryStream mem = null;
                if (s.GetType() == typeof(MemoryStream))
                {
                    mem = (MemoryStream)s;
                }
                else
                {
                    MoSync.Util.CriticalError("Only binaries (non-ubins) are allowed for maConn(Read/Write)(To/From)Data");
                }

                cd(c, mem.GetBuffer(),
                        delegate(int handle, int connOp, int result)
                        {
                            runtime.SetResourceRaw(_data, res);
                            mResultHandler(handle, connOp, result);
                        });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                        delegate(Connection c, byte[] buf, ResultHandler rh)
                        {
                            c.recv(buf, _offset, _size, rh);
                        });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                        delegate(Connection c, byte[] buf, ResultHandler rh)
                        {
                            c.write(buf, _offset, _size, rh);
                        });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maHttpCreate(" + url + ")\n");
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                if (value.Length > 0)
                    c.setRequestHeader(key, value);
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
 public override void connect(ResultHandler rh)
 {
     if (mStream != null) // POST
     {
         mStream.Close();
         mStream = null;
     }
     mRequest.BeginGetResponse(new AsyncCallback(RespCallback), rh);
 }
Esempio n. 43
0
 public ResultHandler RefreshToken(string email)
 {
     return(ResultHandler.HandleTaskResult(new TaskResult <string>(GenerateJwt(email))));
 }
 public override void write(byte[] buffer, int offset, int size,
      ResultHandler rh)
 {
     if (mResponse != null)
         throw new Exception("HTTP write");
     if (mStream == null)
     {
         mRequest.BeginGetRequestStream(
             new AsyncCallback(delegate(IAsyncResult ar)
         {
             mStream = mRequest.EndGetRequestStream(ar);
             mStream.BeginWrite(buffer, offset, size,
                 new AsyncCallback(WriteCallback), rh);
         }), rh);
         return;
     }
     mStream.BeginWrite(buffer, offset, size,
         new AsyncCallback(WriteCallback), rh);
 }
Esempio n. 45
0
 public async Task <ResultHandler> SetCompanyDetails(SetCompanyDetailsDto data, string email)
 {
     return(ResultHandler.HandleTaskResult(await repository.SetCompanyDetails(data, email)));
 }
        public void createSummaryFile(BrowserType browser)
        {
            DateTime timeNow = DateTime.Now;
            string fileFormat = string.Format("Date {0}_{1}_{2} Time {3}_{4}_{5}", timeNow.Month, timeNow.Day, timeNow.Year, timeNow.Hour, timeNow.Minute, timeNow.Second);

            ResultHandler = new ResultHandler("TestSummary_" + DateTime.Now, browser, TestsRun);
            ResultHandler.SaveResultsAsHtml(ResultPath + "TestSummary_" + fileFormat + ".html");
        }
Esempio n. 47
0
 public override void write(byte[] buffer, int offset, int size,
                            ResultHandler rh)
 {
     mSocket.SendAsync(setupRW(buffer, offset, size, rh, MoSync.Constants.CONNOP_WRITE));
 }
Esempio n. 48
0
            protected void RespCallback(IAsyncResult ar)
            {
                int           result;
                ResultHandler rh = (ResultHandler)ar.AsyncState;

                try
                {
                    mResponse = mRequest.EndGetResponse(ar);
                    mStream   = mResponse.GetResponseStream();
                    if (mResponse is HttpWebResponse)
                    {
                        result = (int)((HttpWebResponse)mResponse).StatusCode;
                    }
                    else
                    {
                        result = 1;
                    }
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        mResponse = e.Response;
                        mStream   = mResponse.GetResponseStream();
                    }
                    switch (e.Status)
                    {
                    case WebExceptionStatus.ProtocolError:
                        if (e.Response is HttpWebResponse)
                        {
                            result = (int)((HttpWebResponse)mResponse).StatusCode;
                        }
                        else
                        {
                            result = MoSync.Constants.CONNERR_GENERIC;
                        }
                        break;

                    case WebExceptionStatus.NameResolutionFailure:
                    case WebExceptionStatus.ProxyNameResolutionFailure:
                        result = MoSync.Constants.CONNERR_DNS;
                        break;

                    case WebExceptionStatus.ConnectionClosed:
                        result = MoSync.Constants.CONNERR_CLOSED;
                        break;

                    case WebExceptionStatus.RequestCanceled:
                        result = MoSync.Constants.CONNERR_CANCELED;
                        break;

                    case WebExceptionStatus.SecureChannelFailure:
                    case WebExceptionStatus.TrustFailure:
                        result = MoSync.Constants.CONNERR_SSL;
                        break;

                    case WebExceptionStatus.ServerProtocolViolation:
                        result = MoSync.Constants.CONNERR_PROTOCOL;
                        break;

                    default:
                        result = MoSync.Constants.CONNERR_GENERIC;
                        break;
                    }
                }
                rh(mHandle, MoSync.Constants.CONNOP_CONNECT, result);
            }
 public abstract void write(byte[] buffer, int offset, int size, ResultHandler rh);
Esempio n. 50
0
 public override void recv(byte[] buffer, int offset, int size,
                           ResultHandler rh)
 {
     mStream.BeginRead(buffer, offset, size, new AsyncCallback(RecvCallback), rh);
 }
 public override void recv(byte[] buffer, int offset, int size,
      ResultHandler rh)
 {
     mSocket.ReceiveAsync(setupRW(buffer, offset, size, rh));
 }
        public void Can_invoke_operations_accross_boundaries()
        {
            var outputDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(outputDirectory);
            try
            {
                var pathToEFAssembly = Path.Combine(outputDirectory, "EntityFramework.dll");
                File.Copy(new Uri(typeof(DbContext).Assembly.CodeBase).LocalPath, pathToEFAssembly);
                File.Copy(
                    new Uri(typeof(SqlProviderServices).Assembly.CodeBase).LocalPath,
                    Path.Combine(outputDirectory, "EntityFramework.SqlServer.dll"));
                var pathToConfig = Path.Combine(outputDirectory, "ConsoleApplication1.exe.config");
                File.WriteAllText(pathToConfig, Config);

                using (var compiler = new CSharpCodeProvider())
                {
                    var results = compiler.CompileAssemblyFromSource(
                        new CompilerParameters(
                            new[] { pathToEFAssembly },
                            Path.Combine(outputDirectory, "ConsoleApplication1.exe")),
                        Source);
                    if (results.Errors.HasErrors)
                    {
                        Debug.Fail(results.Errors.Cast<CompilerError>().FirstOrDefault(e => !e.IsWarning).ToString());
                    }

                    var domain = AppDomain.CreateDomain(
                        "BasicDesignTimeScenarios",
                        null,
                        new AppDomainSetup
                        {
                            ApplicationBase = Path.GetDirectoryName(results.PathToAssembly),
                            ConfigurationFile = pathToConfig,
                            ShadowCopyFiles = "true"
                        });
                    try
                    {
                        var executor = domain.CreateInstanceAndUnwrap(
                            typeof(Executor).Assembly.GetName().Name,
                            typeof(Executor).FullName,
                            false,
                            BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance,
                            null,
                            new[] { results.PathToAssembly, null },
                            null,
                            null);
                        var handler = new ResultHandler();
                        domain.CreateInstance(
                            typeof(Executor.GetProviderServices).Assembly.GetName().Name,
                            typeof(Executor.GetProviderServices).FullName,
                            false,
                            BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance,
                            null,
                            new[] { executor, handler, "System.Data.SqlClient", null },
                            null,
                            null);

                        Assert.Equal(typeof(SqlProviderServices).AssemblyQualifiedName, handler.Result);
                    }
                    finally
                    {
                        AppDomain.Unload(domain);
                    }
                }
            }
            finally
            {
                Directory.Delete(outputDirectory, recursive: true);
            }
        }
            private SocketAsyncEventArgs setupRW(byte[] buffer, int offset, int size,
                 ResultHandler rh)
            {
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

                // Setup the buffer to receive the data
                socketEventArg.SetBuffer(buffer, offset, size);

                // Inline event handler for the Completed event.
                // Note: This even handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(
                    delegate(object s, SocketAsyncEventArgs e)
                    {
                        int result;
                        if (e.SocketError == SocketError.Success)
                        {
                            result = e.BytesTransferred;
                        }
                        else
                        {
                            result = MoSync.Constants.CONNERR_GENERIC;
                        }
                        rh(mHandle, MoSync.Constants.CONNOP_READ, result);
                    });
                return socketEventArg;
            }
Esempio n. 54
0
        public static async void UploadImageFromBitmap(String conversationID, BitmapSource image, ResultHandler handler, ErrorHandler errorHandler)
        {
            try
            {
                HttpClient httpClient = new HttpClient();

                httpClient.DefaultRequestHeaders.Add(ClientSession.HeaderToken, ChatConnection.Instance.Session.SessionID);

                MultipartFormDataContent form = new MultipartFormDataContent();

                MemoryStream stream = new MemoryStream();

                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(image));
                enc.Save(stream);

                form.Add(new StreamContent(stream), "file", "Clipboard.jpg");

                String address = ChatConnection.Instance.WebHost;
                int    port    = ChatConnection.Instance.WebPort;
                String url     = String.Format(MediaUploadUrl, address, port, conversationID);

                HttpResponseMessage response = await httpClient.PostAsync(url, form);

                response.EnsureSuccessStatusCode();
                httpClient.Dispose();

                string sd = response.Content.ReadAsStringAsync().Result;

                //Dic<FileName, FileID>
                Dictionary <String, String> result = JsonConvert.DeserializeObject <Dictionary <String, String> >(sd);
                handler(result);
            }
            catch (Exception e)
            {
                if (errorHandler != null)
                {
                    errorHandler(e);
                }
            }
        }
 public override void recv(byte[] buffer, int offset, int size,
      ResultHandler rh)
 {
     mStream.BeginRead(buffer, offset, size, new AsyncCallback(RecvCallback), rh);
 }
Esempio n. 56
0
 public MathService()
 {
     MathDelegate  = AddNumbers;
     MathDelegate += MultiplyNumbers;
 }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach(KeyValuePair<int, Connection> p in mConnections) {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MAEvent_type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MAConnEventData_handle, handle);
                evt.WriteInt32(MAConnEventData_opType, connOp);
                evt.WriteInt32(MAConnEventData_result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                Uri uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return MoSync.Constants.CONNERR_GENERIC;
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                Connection c = mConnections[_conn];
                return c.getAddr(_addr);
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                CommDelegate cd)
            {
                Connection c = mConnections[_conn];
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory mem = (Memory)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                cd(c, mem.GetData(),
                    delegate(int handle, int connOp, int result)
                    {
                        runtime.SetResourceRaw(_data, res);
                        mResultHandler(handle, connOp, result);
                    });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                    delegate(Connection c, byte[] buf, ResultHandler rh)
                    {
                        c.recv(buf, _offset, _size, rh);
                    });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                    delegate(Connection c, byte[] buf, ResultHandler rh)
                    {
                        c.write(buf, _offset, _size, rh);
                    });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                c.setRequestHeader(key, value);
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
Esempio n. 58
0
 public override void recv(byte[] buffer, int offset, int size,
                           ResultHandler rh)
 {
     mSocket.ReceiveAsync(setupRW(buffer, offset, size, rh, MoSync.Constants.CONNOP_READ));
 }