Exemplo n.º 1
0
        public JsonResponse onSettings(Dictionary <string, object> parameters)
        {
            JsonError error = null;

            Dictionary <string, object> status_array = new Dictionary <string, object>();

            status_array.Add("serverName", Node.settings.getOption("serverName", Config.botName));
            status_array.Add("serverDescription", Node.settings.getOption("serverDescription", ""));
            status_array.Add("serverPassword", Node.settings.getOption("serverPassword", ""));
            status_array.Add("allowFileTransfer", Node.settings.getOption("allowFileTransfer", "0"));
            status_array.Add("fileTransferLimitMB", Node.settings.getOption("fileTransferLimitMB", "10"));
            status_array.Add("defaultGroup", Node.groups.groupIndexToName(Int32.Parse(Node.settings.getOption("defaultGroup", "0"))));
            status_array.Add("defaultChannel", Node.channels.channelIndexToName(Int32.Parse(Node.settings.getOption("defaultChannel", "0"))));
            int intro = 0;

            if (Node.settings.getOption("serverName", "") == "")
            {
                intro = 1;
            }
            else if (Node.channels.channels.Count == 0)
            {
                intro = 2;
            }
            else if (Node.groups.groups.Count == 0)
            {
                intro = 3;
            }
            status_array.Add("intro", intro.ToString());

            return(new JsonResponse {
                result = status_array, error = error
            });
        }
Exemplo n.º 2
0
        public JsonResponse onNewChannel(Dictionary <string, object> parameters)
        {
            JsonError error = null;

            if (Node.channels.hasChannel((string)parameters["channel"]))
            {
                return(new JsonResponse {
                    result = null, error = new JsonError()
                    {
                        code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Channel already exists."
                    }
                });
            }

            BotChannel channel = new BotChannel(Node.channels.getNextIndex(), (string)parameters["channel"]);

            Node.channels.setChannel((string)parameters["channel"], channel);
            if ((string)parameters["default"] == "1")
            {
                Node.settings.setOption("defaultChannel", channel.index.ToString());
            }
            Node.settings.saveSettings();

            Messages.addChannel(channel);

            return(new JsonResponse {
                result = "", error = error
            });
        }
Exemplo n.º 3
0
        public async Task <Session> Login(UserModel user)
        {
            // Create Server endpoint
            Uri functionUri = new Uri(Server.BaseUri + Server.LoginEndpoint);


            // Create a json object for session
            JsonSession jsonSession = new JsonSession(user);

            // Serialize object to json
            string json = JsonConvert.SerializeObject(jsonSession);

            // Do post
            HttpResponseMessage response = await PostAsync(functionUri, json);

            string content = await response.Content.ReadAsStringAsync();

            JsonSession jsonDataBack = new JsonSession();

            if (response.IsSuccessStatusCode)
            {
                // Deserialize response received from Server
                jsonDataBack = JsonConvert.DeserializeObject <JsonSession>(content);

                return(new Session(jsonDataBack));
            }
            else
            {
                JsonError jsonError = JsonConvert.DeserializeObject <JsonError>(content);
                //throw new HttpException(jsonError.Code, jsonError.Status, jsonError.Message);
            }


            return(new Session(new JsonSession()));
        }
Exemplo n.º 4
0
        public async Task <bool> SignUp(Models.UserModel user)
        {
            try {
                // Create uri for server endpoint
                Uri functionUri = new Uri(Server.BaseUri + Server.SignUpEndpoint);
                //Uri functionUri = new Uri(baseUri, Server.SignUpEndpoint);

                // Create json object for user
                JsonUser jsonUser = new JsonUser(user);

                // serialize object to json
                string json = JsonConvert.SerializeObject(jsonUser);

                // do post get response
                HttpResponseMessage response = await PostAsync(functionUri, json);

                if (!response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    JsonError jsonError = JsonConvert.DeserializeObject <JsonError>(content);

                    //throw new HttpException(jsonError.Code, jsonError.Status, jsonError.Message);
                    // throw new Exception();
                }

                return(true);
            } catch (Exception e) {
                Debug.WriteLine(e);
                return(false);
            }
        }
        public async Task Setfullfilepath(JObject fullfilepathJson)
        {
            DebugHandler.TraceMessage("Setfullfilepath Called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(fullfilepathJson.ToString(), DebugSource.TASK, DebugType.PARAMETERS);
            try
            {
                string path = fullfilepathJson.Value <string>("path");
                DirectoryHandler.CreateDirectory(path, "");
                IrcSettings.fullfilepath = path;
                SetAllIrcSettings(IrcSettings);
                SettingsHandler.WriteIrcSettings(IrcSettings);
                await GetCurrentIrcSettings();
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING);

                JsonError jsonError = new JsonError
                {
                    type         = "set_download_directory_error",
                    errortype    = "Exception",
                    errormessage = "Failed to set custom download directory.",
                    exception    = e.ToString()
                };

                await WebSocketHandler.SendMessage(jsonError.ToJson());
            }
        }
Exemplo n.º 6
0
        public JsonResult GetList(int pageNo, int pageSize, string searchText, string filterText, string orderColumn, string orderDesc)
        {
            try
            {
                using (DBManager db = new DBManager())
                {
                    string procedureName         = "CPK.uspReportList";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    paraList.Add(Common.GetParameter("PageNo", DbType.Int32, Convert.ToInt32(pageNo), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("PageSize", DbType.Int32, Convert.ToInt32(pageSize), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("ReportName", DbType.String, searchText, ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("IsActive", DbType.String, filterText, ParameterDirection.Input));
                    if (orderColumn != null && orderColumn.Length != 0)
                    {
                        paraList.Add(Common.GetParameter("Sort", DbType.String, orderColumn + orderDesc, ParameterDirection.Input));
                        procedureName = "CPK.uspReportListSort";
                    }

                    DataSet DbSet = db.GetSelectQuery(paraList, procedureName);
                    ListViewModel <ReportAdmin> listView   = Common.DataToClass <ListViewModel <ReportAdmin> >(DbSet.Tables[0].Rows[0]);
                    List <ReportAdmin>          reportList = Common.DataToList <ReportAdmin>(DbSet.Tables[1]);
                    listView.Rows = reportList;
                    return(Json(listView, JsonRequestBehavior.DenyGet));
                }
            }
            catch (Exception ex)
            {
                JsonError e = new JsonError(ex.Message);
                return(Json(e, JsonRequestBehavior.DenyGet));
            }
        }
        public async Task SetIrcSettings(JObject jsonIrcSettings)
        {
            DebugHandler.TraceMessage("SetIrcSettings Called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(jsonIrcSettings.ToString(), DebugSource.TASK, DebugType.PARAMETERS);

            try
            {
                IrcSettings = SettingsHandler.GetIrcSettings();

                IrcSettings.ServerAddress = jsonIrcSettings.Value <string>("address");
                IrcSettings.Channels      = jsonIrcSettings.Value <string>("channels");
                IrcSettings.UserName      = jsonIrcSettings.Value <string>("username");
                IrcSettings.fullfilepath  = jsonIrcSettings.Value <string>("fullfilepath");
                IrcSettings.Port          = jsonIrcSettings.Value <int>("port");
                IrcSettings.Secure        = jsonIrcSettings.Value <bool>("secure");

                SetAllIrcSettings(IrcSettings);
                SettingsHandler.WriteIrcSettings(IrcSettings);
                await GetCurrentIrcSettings();
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING);

                JsonError jsonError = new JsonError
                {
                    type         = "set_irc_settings_error",
                    errortype    = "Exception",
                    errormessage = "Failed to set irc settings.",
                    exception    = e.ToString()
                };

                await WebSocketHandler.SendMessage(jsonError.ToJson());
            }
        }
        public async Task SetLittleWeebSettings(JObject jsonLittleWeebSettings)
        {
            DebugHandler.TraceMessage("SetLittleWeebSettings Called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(jsonLittleWeebSettings.ToString(), DebugSource.TASK, DebugType.PARAMETERS);

            try
            {
                LittleWeebSettings = SettingsHandler.GetLittleWeebSettings();

                LittleWeebSettings.RandomUsernameLength = jsonLittleWeebSettings.Value <int>("randomusernamelength");
                LittleWeebSettings.DebugLevel           = jsonLittleWeebSettings.Value <JArray>("debuglevel").ToObject <List <int> >();
                LittleWeebSettings.DebugType            = jsonLittleWeebSettings.Value <JArray>("debugtype").ToObject <List <int> >();
                LittleWeebSettings.MaxDebugLogSize      = jsonLittleWeebSettings.Value <int>("maxdebuglogsize");
                SetAllLittleWeebSettings(LittleWeebSettings);


                SettingsHandler.WriteLittleWeebSettings(LittleWeebSettings);

                await GetCurrentLittleWeebSettings();
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING);
                JsonError error = new JsonError
                {
                    type         = "set_littleweeb_settings_error",
                    errortype    = "Exception",
                    errormessage = "Failed to set littleweeb settings.",
                    exception    = e.ToString()
                };

                await WebSocketHandler.SendMessage(error.ToJson());
            }
        }
Exemplo n.º 9
0
        public JsonResult RemoveCheck(string selectedGroup)
        {
            try
            {
                using (DBManager db = new DBManager())
                {
                    string procedureName         = "CPK.uspGroupRemoveCheck";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    if (selectedGroup == null || selectedGroup == "" || selectedGroup == "0")
                    {
                        return(Json(new List <Int32>()
                        {
                            -1, -1, -1
                        }, JsonRequestBehavior.AllowGet));
                    }
                    paraList.Add(Common.GetParameter("GroupID", DbType.Int32, Convert.ToInt32(selectedGroup), ParameterDirection.Input));

                    DataSet      DbSet       = db.GetSelectQuery(paraList, procedureName);
                    List <Int32> removeCheck = new List <Int32>();
                    removeCheck.Add((Int32)DbSet.Tables[0].Rows[0].ItemArray[0]);  // report count
                    removeCheck.Add((Int32)DbSet.Tables[1].Rows[0].ItemArray[0]);  // user count
                    removeCheck.Add((Int32)DbSet.Tables[2].Rows[0].ItemArray[0]);  // child group count
                    return(Json(removeCheck, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                JsonError e = new JsonError(ex.Message);
                return(Json(e, JsonRequestBehavior.DenyGet));
            }
        }
Exemplo n.º 10
0
        public string DeleteDirectory(string path)
        {
            DebugHandler.TraceMessage("DeleteDirectory Called", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage("Directory Path: " + path, DebugSource.TASK, DebugType.PARAMETERS);
            try
            {
                DirectoryInfo info          = new DirectoryInfo(path);
                int           amountOfFiles = info.GetFiles().Length;
                if (amountOfFiles == 0)
                {
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path);

                        JsonSuccess report = new JsonSuccess()
                        {
                            message = "Succesfully deleted folder with path: " + path
                        };

                        return(report.ToJson());
                    }
                    else
                    {
                        JsonSuccess report = new JsonSuccess()
                        {
                            message = "Directory with path : " + path + " already removed."
                        };

                        return(report.ToJson());
                    }
                }
                else
                {
                    DebugHandler.TraceMessage("Could not delete directory: " + path + " because there are still files and/or other directories inside!", DebugSource.TASK, DebugType.WARNING);


                    JsonError jsonError = new JsonError
                    {
                        type         = "delete_directory_warning",
                        errortype    = "warning",
                        errormessage = "Could not delete directory: " + path + " because there are still files and/or other directories inside!"
                    };

                    return(jsonError.ToJson());
                }
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage("Could not delete directory: " + e.ToString(), DebugSource.TASK, DebugType.WARNING);

                JsonError jsonError = new JsonError
                {
                    type         = "delete_directory_error",
                    errortype    = "exception",
                    errormessage = "Could not get drives, see log."
                };

                return(jsonError.ToJson());
            }
        }
Exemplo n.º 11
0
        public JsonResult GetListByGroup(string filterText, string userID)
        {
            try
            {
                using (DBManager db = new DBManager())
                {
                    string nameOfProcedure       = "CPK.uspUserListByGroup";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    // paraList.Add(Common.GetParameter("PageNo", DbType.Int32, Convert.ToInt32(pageNo), ParameterDirection.Input));
                    //paraList.Add(Common.GetParameter("PageSize", DbType.Int32, Convert.ToInt32(pageSize), ParameterDirection.Input));
                    // paraList.Add(Common.GetParameter("FullName", DbType.String, searchText, ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("GroupId", DbType.Int32, Convert.ToInt32(filterText), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("UserId", DbType.String, userID, ParameterDirection.Input));

                    DataSet DbSet = db.GetSelectQuery(paraList, nameOfProcedure);
                    ListViewModel <UserListViewModel> listView = Common.DataToClass <ListViewModel <UserListViewModel> >(DbSet.Tables[0].Rows[0]);
                    List <UserListViewModel>          userList = Common.DataToList <UserListViewModel>(DbSet.Tables[1]);
                    listView.Rows = userList;
                    return(Json(listView, JsonRequestBehavior.DenyGet));
                }
            }
            catch (Exception ex)
            {
                JsonError e = new JsonError(ex.Message);
                return(Json(e, JsonRequestBehavior.DenyGet));
            }
        }
Exemplo n.º 12
0
        public JsonResponse onUpdateChannel(Dictionary <string, object> parameters)
        {
            JsonError error = null;

            if (!Node.channels.hasChannel((string)parameters["origChannel"]))
            {
                return(new JsonResponse {
                    result = null, error = new JsonError()
                    {
                        code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Unknown channel."
                    }
                });
            }

            var orig_channel = Node.channels.getChannel((string)parameters["origChannel"]);

            Node.channels.setChannel(orig_channel.channelName, new BotChannel(orig_channel.index, (string)parameters["channel"]));
            if ((string)parameters["default"] == "1")
            {
                Node.settings.setOption("defaultChannel", orig_channel.index.ToString());
            }
            Node.settings.saveSettings();

            return(new JsonResponse {
                result = "", error = error
            });
        }
Exemplo n.º 13
0
        private async void OnIrcClientConnectionStatusEvent(object sender, IrcClientConnectionStatusArgs args)
        {
            DebugHandler.TraceMessage("OnIrcClientConnectionStatusEvent called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(args.ToString(), DebugSource.TASK, DebugType.PARAMETERS);


            IsIrcConnected = args.Connected;

            try
            {
                JsonIrcInfo update = new JsonIrcInfo()
                {
                    connected    = args.Connected,
                    channel      = args.CurrentIrcSettings.Channels,
                    server       = args.CurrentIrcSettings.ServerAddress,
                    user         = args.CurrentIrcSettings.UserName,
                    fullfilepath = args.CurrentIrcSettings.fullfilepath
                };

                await WebSocketHandler.SendMessage(update.ToJson());
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.ERROR);
                JsonError error = new JsonError()
                {
                    type         = "irc_status_error",
                    errormessage = "Error on sending irc status update to client.",
                    errortype    = "exception",
                    exception    = e.ToString()
                };
                await WebSocketHandler.SendMessage(error.ToJson());
            }
        }
        public async Task AbortDownload(JObject downloadJson)
        {
            DebugHandler.TraceMessage("AbortDownload called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(downloadJson.ToString(), DebugSource.TASK, DebugType.PARAMETERS);
            string id       = downloadJson.Value <string>("id");
            string filePath = downloadJson.Value <string>("path");

            if (id != null)
            {
                string result = await DownloadHandler.AbortDownload(id);

                await WebSocketHandler.SendMessage(result);
            }
            else if (filePath != null)
            {
                string result = await DownloadHandler.AbortDownload(null, filePath);

                await WebSocketHandler.SendMessage(result);
            }
            else
            {
                DebugHandler.TraceMessage("Neither id or file path have been defined!", DebugSource.TASK, DebugType.WARNING);
                JsonError error = new JsonError()
                {
                    type         = "parse_download_to_abort_error",
                    errormessage = "Neither id or file path have been defined!",
                    errortype    = "warning",
                    exception    = "none"
                };
                await WebSocketHandler.SendMessage(error.ToJson());
            }
        }
Exemplo n.º 15
0
        public JsonResult GetListReceive(int pageNo, int pageSize, string searchText, string filterText, string orderColumn, string orderDesc)
        {
            try
            {
                using (DBManager db = new DBManager())
                {
                    string UserID                = User.Identity.Name;
                    string procedureName         = "CPK.uspMessageReceiveList";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    paraList.Add(Common.GetParameter("PageNo", DbType.Int32, Convert.ToInt32(pageNo), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("PageSize", DbType.Int32, Convert.ToInt32(pageSize), ParameterDirection.Input));
                    if (User.IsInRole("Admin"))
                    {
                        UserID = "Administrator";
                    }
                    paraList.Add(Common.GetParameter("UserID", DbType.String, UserID, ParameterDirection.Input));

                    DataSet DbSet = db.GetSelectQuery(paraList, procedureName);
                    ListViewModel <MessageReceiveModel> listView    = Common.DataToClass <ListViewModel <MessageReceiveModel> >(DbSet.Tables[0].Rows[0]);
                    List <MessageReceiveModel>          MessageList = Common.DataToList <MessageReceiveModel>(DbSet.Tables[1]);
                    listView.Rows = MessageList;
                    return(Json(listView, JsonRequestBehavior.DenyGet));
                }
            }
            catch (Exception ex)
            {
                JsonError e = new JsonError(ex.Message);
                return(Json(e, JsonRequestBehavior.DenyGet));
            }
        }
Exemplo n.º 16
0
        public async Task DeleteDirectory(JObject directoryJson)
        {
            DebugHandler.TraceMessage("DeleteDirectory called.", DebugSource.TASK, DebugType.ENTRY_EXIT);
            DebugHandler.TraceMessage(directoryJson.ToString(), DebugSource.TASK, DebugType.PARAMETERS);
            try
            {
                string filePath = directoryJson.Value <string>("path");
                if (filePath.Contains("//"))
                {
                    filePath.Replace("//", "/");
                }

                if (filePath.Contains("\\\\"))
                {
                    filePath.Replace("\\\\", "\\");
                }
                string result = DirectoryHandler.DeleteDirectory(filePath);
                await WebSocketHandler.SendMessage(result);
            }
            catch (Exception e)
            {
                DebugHandler.TraceMessage(e.ToString(), DebugSource.TASK, DebugType.WARNING);

                JsonError error = new JsonError()
                {
                    type         = "create_directory_error",
                    errormessage = "Could not create directory.",
                    errortype    = "exception",
                    exception    = e.ToString()
                };

                await WebSocketHandler.SendMessage(error.ToJson());
            }
        }
Exemplo n.º 17
0
        public static void HandleError(HttpResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new JsonErrorHandler
                          ()
                      {
                          ErrorCode        = (int)HttpStatusCode.Unauthorized,
                          ReferenceLink    = "",
                          ErrorDescription = "No está authorizado para realizar esta acción",
                          HttpStatus       = HttpStatusCode.Unauthorized,
                      }
            }
            ;

            JsonError ap = JsonConvert.DeserializeObject <JsonError>(response.Content.ReadAsStringAsync().Result);

            throw new JsonErrorHandler
                      ()
                  {
                      ErrorCode        = ap.ErrorCode,
                      ReferenceLink    = ap.ReferenceLink,
                      ErrorDescription = ap.ErrorDescription,
                      HttpStatus       = ap.HttpStatus
                  };
        }
Exemplo n.º 18
0
        public JsonResult RemoveMember(FormCollection collection)
        {
            try
            {
                var rolename = collection["RoleName"];
                var username = collection["Username"];

                if (!string.IsNullOrWhiteSpace(rolename) && !string.IsNullOrWhiteSpace(username))
                {
                    Context.UserLog.LogEntry(new RFUserLogEntry
                    {
                        Action       = "RemoveMember",
                        Area         = "Role",
                        IsUserAction = true,
                        IsWarning    = false,
                        Username     = Username,
                        Description  = String.Format("Removed user {0} from role {1}", username, rolename)
                    });
                    return(Json(Context.UserRole.RemoveMember(rolename, username)));
                }
            }
            catch (Exception ex)
            {
                return(Json(JsonError.Throw("RemoveMember", ex)));
            }
            return(Json(JsonError.Throw("RemoveMember", "Internal system error.")));
        }
Exemplo n.º 19
0
        public async Task <ActionResult <string> > Post()
        {
            string       jsonOut     = "{err=not_recognized}";
            string       respBody    = await new StreamReader(Request.Body).ReadToEndAsync();
            string       contentType = Request.ContentType;
            StringValues userAgent;

            Request.Headers.TryGetValue("User-Agent", out userAgent);

            JsonError jerr = new JsonError
            {
                operation         = "fetch csp",
                error             = "invalid request",
                error_description = "must be at least 3 parts to a jose request"
            };

            string[] splitBody = respBody.Split('.');
            if (splitBody.Length < 3)
            {
                string jeOut             = JsonSerializer.Serialize(jerr);
                CredentialDocResult cdr1 = new CredentialDocResult("{\"alg\": \"RS256\"}", jeOut, 0);
                return((await cdr1.SignCDR(_kss))[0]);
            }

            string json = "{ }";

            return(CreatedAtAction("Post", jsonOut));
        }
Exemplo n.º 20
0
 public JsonResult IgnoreError(string dp)
 {
     try
     {
         if (!dp.IsBlank())
         {
             _systemContext.DispatchStore.Ignored(dp);
             Context.UserLog.LogEntry(new RFUserLogEntry
             {
                 Action       = "Ignore Error",
                 Area         = "Error Queue",
                 Description  = String.Format("Ignored error on processor {0}", dp),
                 IsUserAction = true,
                 IsWarning    = false,
                 Timestamp    = DateTimeOffset.Now,
                 Username     = Username,
             });
             return(GetErrorQueue());
         }
         return(Json(JsonError.Throw("IgnoreError", "System error: blank key")));
     }
     catch (Exception ex)
     {
         return(Json(JsonError.Throw("IgnoreError", ex)));
     }
 }
Exemplo n.º 21
0
        public JsonResponse onGetWallet(Dictionary <string, object> parameters)
        {
            if (!parameters.ContainsKey("id"))
            {
                JsonError error = new JsonError {
                    code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Parameter 'id' is missing"
                };
                return(new JsonResponse {
                    result = null, error = error
                });
            }

            // Show own address, balance and blockchain synchronization status
            byte[] address = Base58Check.Base58CheckEncoding.DecodePlain((string)parameters["id"]);
            Wallet w       = Node.walletState.getWallet(address);

            Dictionary <string, string> walletData = new Dictionary <string, string>();

            walletData.Add("id", Base58Check.Base58CheckEncoding.EncodePlain(w.id));
            walletData.Add("balance", w.balance.ToString());
            walletData.Add("type", w.type.ToString());
            walletData.Add("requiredSigs", w.requiredSigs.ToString());
            if (w.allowedSigners != null)
            {
                if (w.allowedSigners != null)
                {
                    walletData.Add("allowedSigners", "(" + (w.allowedSigners.Length + 1) + " keys): " +
                                   w.allowedSigners.Aggregate(Base58Check.Base58CheckEncoding.EncodePlain(w.id), (aggr, n) => aggr += "," + Base58Check.Base58CheckEncoding.EncodePlain(n), aggr => aggr)
                                   );
                }
                else
                {
                    walletData.Add("allowedSigners", "null");
                }
            }
            else
            {
                walletData.Add("allowedSigners", "null");
            }
            if (w.data != null)
            {
                walletData.Add("extraData", Crypto.hashToString(w.data));
            }
            else
            {
                walletData.Add("extraData", "null");
            }
            if (w.publicKey != null)
            {
                walletData.Add("publicKey", Crypto.hashToString(w.publicKey));
            }
            else
            {
                walletData.Add("publicKey", "null");
            }

            return(new JsonResponse {
                result = walletData, error = null
            });
        }
Exemplo n.º 22
0
        public JsonResult GetList(int pageNo, int pageSize, string searchText, string userID, string orderColumn, string orderDesc)
        {
            try
            {
                using (DBManager db = new DBManager())
                {
                    string nameOfProcedure       = "CPK.uspUserList";
                    List <SqlParameter> paraList = new List <SqlParameter>();
                    paraList.Add(Common.GetParameter("PageNo", DbType.Int32, Convert.ToInt32(pageNo), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("PageSize", DbType.Int32, Convert.ToInt32(pageSize), ParameterDirection.Input));
                    paraList.Add(Common.GetParameter("FullName", DbType.String, searchText, ParameterDirection.Input));

                    if (!AccountHelper.isEmpty(orderColumn))
                    {
                        paraList.Add(Common.GetParameter("Sort", DbType.String, orderColumn + orderDesc, ParameterDirection.Input));
                        nameOfProcedure = "CPK.uspUserListSort";
                    }

                    DataSet DbSet = db.GetSelectQuery(paraList, nameOfProcedure);
                    ListViewModel <UserListViewModel> listView = Common.DataToClass <ListViewModel <UserListViewModel> >(DbSet.Tables[0].Rows[0]);
                    List <UserListViewModel>          userList = Common.DataToList <UserListViewModel>(DbSet.Tables[1]);
                    listView.Rows = userList;
                    return(Json(listView, JsonRequestBehavior.DenyGet));
                }
            }
            catch (Exception ex)
            {
                JsonError e = new JsonError(ex.Message);
                return(Json(e, JsonRequestBehavior.DenyGet));
            }
        }
Exemplo n.º 23
0
        public JsonResponse onGetTransaction(Dictionary <string, object> parameters)
        {
            if (!parameters.ContainsKey("id"))
            {
                JsonError error = new JsonError {
                    code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Parameter 'id' is missing"
                };
                return(new JsonResponse {
                    result = null, error = error
                });
            }

            string      txid_string = (string)parameters["id"];
            Transaction t           = TransactionPool.getTransaction(txid_string, 0, Config.storeFullHistory);

            if (t == null)
            {
                return(new JsonResponse {
                    result = null, error = new JsonError {
                        code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Transaction not found."
                    }
                });
            }

            return(new JsonResponse {
                result = t.toDictionary(), error = null
            });
        }
Exemplo n.º 24
0
        public JsonResponse onStress(Dictionary <string, object> parameters)
        {
            JsonError error = null;

            string type_string = "txspam";

            if (parameters.ContainsKey("type"))
            {
                type_string = (string)parameters["type"];
            }

            int txnum = 0;

            if (parameters.ContainsKey("num"))
            {
                string txnumstr = (string)parameters["num"];
                try
                {
                    txnum = Convert.ToInt32(txnumstr);
                }
                catch (OverflowException)
                {
                    txnum = 0;
                }
            }


            // Used for performing various tests.
            StressTest.start(type_string, txnum);

            return(new JsonResponse {
                result = "Stress test started", error = error
            });
        }
Exemplo n.º 25
0
        public JsonResponse onGetLastBlocks()
        {
            JsonError error = null;

            Dictionary <string, string>[] blocks = new Dictionary <string, string> [10];
            long blockCnt = Node.blockChain.Count > 10 ? 10 : Node.blockChain.Count;

            for (ulong i = 0; i < (ulong)blockCnt; i++)
            {
                Block block = Node.blockChain.getBlock(Node.blockChain.getLastBlockNum() - i);
                if (block == null)
                {
                    error = new JsonError {
                        code = (int)RPCErrorCode.RPC_INTERNAL_ERROR, message = "An unknown error occured, while getting one of the last 10 blocks."
                    };
                    return(new JsonResponse {
                        result = null, error = error
                    });
                }

                blocks[i] = blockToJsonDictionary(block);
            }

            return(new JsonResponse {
                result = blocks, error = error
            });
        }
Exemplo n.º 26
0
        async internal Task <T> TryPostAsync <T>(string url, string postData = "")
        {
            int i = 0;

            while (true)
            {
                try
                {
                    string result, tokenParameter = String.Empty;

                    if (!String.IsNullOrWhiteSpace(_token))
                    {
                        tokenParameter = (String.IsNullOrWhiteSpace(postData) ? "" : "&") + "token=" + _token;
                    }

                    try
                    {
                        result = await _http.PostFormUrlEncodedStringAsync(url.UrlAppendParameters(tokenParameter),
                                                                           $"{ postData }{ tokenParameter }");

                        //result = Encoding.UTF8.GetString(await WebFunctions.DownloadRawAsync(url.UrlAppendParameters(tokenParameter),
                        //                                                                     postData == null ? null : Encoding.UTF8.GetBytes(postData),
                        //                                                                     null, null, string.Empty, string.Empty));
                    }
                    catch (WebException ex)
                    {
                        if (ex.Message.Contains("(403)") ||
                            ex.Message.Contains("(499)") ||
                            ex.Message.Contains("(499)"))
                        {
                            throw new TokenRequiredException();
                        }
                        throw ex;
                    }

                    if (result.Contains("\"error\":"))
                    {
                        JsonError error = JsonConvert.DeserializeObject <JsonError>(result);
                        if (error.Error == null)
                        {
                            throw new Exception("Unknown error");
                        }

                        if (error.Error.Code == 499 || error.Error.Code == 498 || error.Error.Code == 403) // Token Required (499), Invalid Token (498), No user Persmissions (403)
                        {
                            throw new TokenRequiredException();
                        }

                        throw new Exception("Error:" + error.Error.Code + "\n" + error.Error.Message);
                    }

                    return(JsonConvert.DeserializeObject <T>(result));
                }
                catch (TokenRequiredException ex)
                {
                    await HandleTokenExceptionAsync(i, ex);
                }
                i++;
            }
        }
Exemplo n.º 27
0
        public string Normalize(string responseData)
        {
            var error     = JsonError.FromJson(responseData);
            var data      = JsonResponse.FromJson(responseData);
            var finalList = new List <List <Dictionary <string, string> > >();

            if (data != null && data.Items != null)
            {
                foreach (Item item in data.Items)
                {
                    List <Dictionary <string, string> > resultArray = IterateThroughRows(item);
                    finalList.Add(resultArray);
                }

                return(JsonConvert.SerializeObject(finalList.SelectMany(x => x), Formatting.Indented, new JsonConverter[] { new StringEnumConverter() }));
            }
            else if (data != null && data.Items == null)
            {
                return(JsonConvert.SerializeObject(data, Formatting.Indented, new JsonConverter[] { new StringEnumConverter() }));
            }
            else
            {
                return(JsonConvert.SerializeObject(error, Formatting.Indented, new JsonConverter[] { new StringEnumConverter() }));
            }
        }
Exemplo n.º 28
0
        public JsonResponse onTestAdd(Dictionary <string, object> parameters)
        {
            if (!parameters.ContainsKey("wallet"))
            {
                JsonError error = new JsonError {
                    code = (int)RPCErrorCode.RPC_INVALID_PARAMETER, message = "Parameter 'wallet' is missing"
                };
                return(new JsonResponse {
                    result = null, error = error
                });
            }

            byte[] wallet = Base58Check.Base58CheckEncoding.DecodePlain((string)parameters["wallet"]);

            string responseString = JsonConvert.SerializeObject("Friend added successfully");

            if (TestClientNode.addFriend(wallet) == false)
            {
                responseString = JsonConvert.SerializeObject("Could not find wallet id or add friend");
            }

            return(new JsonResponse()
            {
                result = responseString, error = null
            });
        }
Exemplo n.º 29
0
        public JsonResponse onTxa(Dictionary <string, object> parameters)
        {
            JsonError error = null;

            string fromIndex = "0";

            if (parameters.ContainsKey("fromIndex"))
            {
                fromIndex = (string)parameters["fromIndex"];
            }

            string count = "50";

            if (parameters.ContainsKey("count"))
            {
                count = (string)parameters["count"];
            }

            Transaction[] transactions = TransactionPool.getAppliedTransactions().Skip(Int32.Parse(fromIndex)).Take(Int32.Parse(count)).ToArray();

            Dictionary <string, Dictionary <string, object> > tx_list = new Dictionary <string, Dictionary <string, object> >();

            foreach (Transaction t in transactions)
            {
                tx_list.Add(t.id, t.toDictionary());
            }

            return(new JsonResponse {
                result = tx_list, error = error
            });
        }
Exemplo n.º 30
0
 public virtual String Delete(dto model, string cookievalue = "")
 {
     using (var client = Factory.CreateClient())
     {
         client.HttpClient.DefaultRequestHeaders.Clear();
         client.HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         client.HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
         if (!String.IsNullOrEmpty(cookievalue))
         {
             client.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", cookievalue);
         }
         string postBody = JsonConvert.SerializeObject(model);
         var    response = client.HttpClient.DeleteAsync((Myurl + "/" + model.Id)).Result;
         if (response.IsSuccessStatusCode)
         {
             resp = "Ok";
             return(resp);
         }
         else
         {
             JsonError ap = JsonConvert.DeserializeObject <JsonError>(response.Content.ReadAsStringAsync().Result);
             resp = ap.Message;
             return(resp);
         }
     }
 }
 public JsonRpcException(JsonError error)
     : base(error.Message)
 {
     _error = error;
 }