System.Threading.Timer: A second operation was started on this context with - timer

I have Console Application on .NET 5 which is Discord Bot.
While start the application i have the problem with this:
System.InvalidOperationException: A second operation was started on
this context before a previous operation completed. This is usually
caused by different threads concurrently using the same instance of
DbContext. For more information on how to avoid threading issues with
DbContext
And this is happens in Timer
This is in constructor:
_approveTimer = new Timer(async delegate
{
await CheckApproveAsync();
}, null, TimeSpan.Zero,
TimeSpan.FromSeconds(30));
public async Task CheckApproveAsync()
{
var pendingUsers = await _pendingUsers.GetAllAsync();
if (pendingUsers is null || !pendingUsers.Any())
return;
Program.Log.Debug($"Checking {pendingUsers.Count} pending users...");
foreach (var user in pendingUsers)
{
var expired = DateTime.UtcNow > user.ExpirationTime;
if (!expired) continue;
await _pendingUsers.DeleteWithDetachAsync(user);
IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
try
{
var msg = await _messageService.GetMessageAsync("register-pending-expired", new FormatData(user.UserId));
await sgUser.SendIonicMessageAsync(msg);
}
catch (Exception ex)
{
await _serverHelper.SendLogAsync(_mainGuildId, "Error", $"{nameof(CheckApproveAsync)} - {ex.Message}");
}
}
var usersValidated = 0;
foreach (var user in pendingUsers)
{
RequestResult codeResult;
string code;
try
{
(codeResult, code) = await GetThirdPartyCodeByEncryptedSummonerIdAsync(user.Region, user.SummonerId);
}
catch (Exception)
{
continue;
}
if (code is null || codeResult != RequestResult.Success)
continue;
var sanitizedCode = new string(code.Where(char.IsLetterOrDigit).ToArray());
if (sanitizedCode != user.ConfirmationCode)
continue;
var (requestResult, summoner) = await GetSummonerByEncryptedPuuIdAsync(user.Region, user.PlayerUUID);
if (requestResult != RequestResult.Success)
{
await _pendingUsers.DeleteWithDetachAsync(user);
continue;
}
var (rankResult, rankData) = await GetLeaguePositionsByEncryptedSummonerIdAsync(user.Region, summoner.Id);
var soloqRank = GetRankModelFromEntry(rankData.FirstOrDefault(x => x.QueueType == "RANKED_SOLO_5x5"));
var summonerIcon = GetSummonerIconUrlById(summoner.ProfileIconId);
var lolData = new LeagueData
{
UserId = user.UserId,
SummonerRegion = user.Region,
PlayerUUID = summoner.Puuid,
AccountId = summoner.AccountId,
SummonerId = summoner.Id,
SummonerName = summoner.Name,
SummonerIcon = summonerIcon,
SummonerLevel = summoner.SummonerLevel,
SummonerRank = $"{soloqRank.Tier} {soloqRank.Rank}"
};
_ = IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
await AssignRoleFromRankAsync(sgUser, soloqRank.Tier);
var data = await _leagueRepository.GetByIdAsync(user.UserId);
if (data == null)
{
await _leagueRepository.AddAsync(lolData);
}
usersValidated++;
user.SummonerName = lolData.SummonerName;
await PostValidateAsync(user);
}
Program.Log.Information($"{usersValidated} users validated.");
}
I read that it can be problem that if some method is not awaited, but i've checked it's all awaited. Which suggestions about this?

Related

.NET MAUI Setting an item SelectedIndex on Page Load is Delayed

When the view appears on the screen there is a short delay setting the values to each control. Is it possible to set the values before the user sees the view?
public UserSettingsView()
{
InitializeComponent();
LoadAsync();
}
private async void LoadAsync()
{
try
{
// Loading data from API
Languages = await _languageService.GetAsync(AccessToken);
USStates = await _uSStateService.GetAsync(AccessToken);
// Assigning the list to the ItemSource of each Picker.
ddlLanguages.ItemsSource = Languages;
ddlUSStates.ItemsSource = USStates;
// Getting the user's preferred settings
var userSettings = await _accountService.GetSettingsAsync(UserID, AccessToken);
if (userSettings != null)
{
// Setting user values to each Picker control.
// This is where the delay happens.
ddlLanguages.SelectedIndex = Languages.FindIndex(x => x.ID == userSettings .LanguageID);
ddlUSStates.SelectedIndex = USStates.FindIndex(x => x.ID == userSettings .USStateID);
cbAge.IsChecked = currentSettings.AgeQualified;
}
}
catch
{
await DisplayAlert("Oh no!", "Error loading the page", "OK");
}
}
To resolve the delay, I am passing the two lists for the languages and the States from the previous page.
public UserSettingsView(List<Language> _languages, List<USState> _usStates)
{
InitializeComponent();
Languages = _languages;
USStates = _usStates;
LoadAsync();
}
private async void LoadAsync()
{
try
{
ddlLanguages.ItemsSource = Languages;
ddlUSStates.ItemsSource = USStates;
var currentSettings = await _accountService.GetSettingsAsync(UserID, AccessToken);
if (currentSettings != null)
{
ddlLanguages.SelectedIndex = Languages.FindIndex(x => x.ID == currentSettings.LanguageID);
ddlUSStates.SelectedIndex = USStates.FindIndex(x => x.ID == currentSettings.USStateID);
switchAgeQualification.IsToggled = currentSettings.AgeQualified;
}
}
catch
{
await DisplayAlert("Error", "Could not load page data", "OK");
}
}
If I understand correctly, you currently have a line like this:
await Navigation.PushModalAsync(new UserSettingsView());
I don't see the types of the properties involved, but the basic idea is to do all the slow awaits BEFORE doing new UserSettingsView....
Something like this:
public class UserSettingsData
{
SomeType1 Languages;
SomeType2 USStates;
SomeType3 UserSettings;
}
...
// Slow await calls.
var data = await UserSettingsView.PrepAsync(UserId, AccessToken);
// Now create and display the view.
await Navigation.PushModalAsync(new UserSettingsView(data));
...
public static async UserSettingsData PrepAsync(SomeType4 UserId, SomeType5 AccessToken)
{
var data = new UserSettingsData();
data.Languages = await _accountService.GetSettingsAsync(...);
data.USStates = await ...;
data.UserSettings = await ...;
}
public UserSettingsView(UserSettingsData data)
{
...
// NOT AN ASYNC METHOD, so happens immediately, before page is shown.
Load(data);
}
// NOT AN ASYNC METHOD, so happens immediately.
private void Load(UserSettingsData data)
{
Languages = data.Languages;
USStates = data.USStates;
var userSettings = data.UserSettings;
...
// if still need DisplayAlert
Dispatcher.InvokeOnMainThread(async () =>
await DisplayAlert...
);
}
Replace "SomeType" etc with your actual types.

EF Core LogIn Taking a Long Time

I'm trying to make an endpoint for logging in with a token in ASP.NET Core. The API is using EFCore, but my code is taking a long time to log me in.
This is the service:
public async Task<AuthModel> GetTokenAsync(UserLoginDto model)
{
var authModel = new AuthModel();
var user = await _userManager.FindByEmailAsync(model.Email);
if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password))
{
authModel.Message = "Email or Password is incorrect!";
return authModel;
}
var jwtSecurityToken = await CreateJwtToken(user);
var rolesList = await _userManager.GetRolesAsync(user);
authModel.IsAuthenticated = true;
authModel.Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
authModel.Email = user.Email;
authModel.Username = user.UserName;
//authModel.ExpiresOn = jwtSecurityToken.ValidTo;
authModel.Roles = rolesList.ToList();
if (user.RefreshTokens.Any(t => t.IsActive))
{
var activeRefreshToken = user.RefreshTokens.FirstOrDefault(t => t.IsActive);
authModel.RefreshToken = activeRefreshToken.Token;
authModel.RefreshTokenExpiration = activeRefreshToken.ExpiresOn;
}
else
{
var refreshToken = GetRefreshToken();
authModel.RefreshToken = refreshToken.Token;
authModel.RefreshTokenExpiration = refreshToken.ExpiresOn;
user.RefreshTokens.Add(refreshToken);
await _userManager.UpdateAsync(user);
}
return authModel;
}
Endpoint:
[HttpPost]
public async Task<ActionResult> Login([FromBody]UserLoginDto loginDto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await _authService.GetTokenAsync(loginDto);
if (!string.IsNullOrEmpty(result.RefreshToken))
{
_authService.SetRefreshTokenInCookie(result.RefreshToken, result.RefreshTokenExpiration);
}
return Ok(result);
}

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

Trying to connect my application with SQL Server using sql_server_socket. In SqlConnection.dart the guinness package's version is not specified right

// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
library sql_server_socket_test;
import '../lib/sqlconnection.dart';
import '../lib/table.dart';
import '../lib/sqlformats.dart';
import 'dart:async';
//Error occurs here(Couldn't get pub because of wrong version specification)
import "package:guinness/guinness.dart";
void main()
{
defineSpecs().then((_){});
}
Future defineSpecs() async
{
/// creates a common database where to perform all tests
var conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=yes;");
//var conn = new SqlConnection("Server=DEVIL\\SQLEXPRESS;Database=master;User Id=sa;Password=;");
await conn.open();
await conn.execute("IF EXISTS (SELECT name FROM master.sys.databases WHERE name = 'sql_server_socket_test_db') DROP DATABASE sql_server_socket_test_db");
await conn.execute("CREATE DATABASE sql_server_socket_test_db");
await conn.execute("USE sql_server_socket_test_db");
await conn.execute("CREATE TABLE Customers (Id INT IDENTITY PRIMARY KEY, Name VARCHAR(64), Age INT, Born DATETIME, HasWebSite BIT NOT NULL)");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite) VALUES ('Bob' ,33, 0)");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite, Born) VALUES ('Tom' ,42, 1, ${sqlDate(new DateTime(1972,05,03))})");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite) VALUES ('Mary',18, 1)");
await conn.close();
conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=sql_server_socket_test_db;Trusted_Connection=yes;");
//conn = new SqlConnection("Server=DEVIL\\SQLEXPRESS;Database=sql_server_socket_test_db;User Id=sa;Password=;");
describe("SQL formatting functions", ()
{
describe("sqlDate()", ()
{
it("returns a SQL formatted date", ()
{
var d = sqlDate(new DateTime(1980,5,3));
expect(d).toEqual("CONVERT(DATETIME,'1980-05-03 00:00:00.000',102)");
});
});
describe("sqlBool()", ()
{
it("converts true and false into 1 and 0", ()
{
expect(sqlBool(false)).toEqual("0");
expect(sqlBool(true )).toEqual("1");
});
});
describe("sqlString()", ()
{
it("sqlString() formats a string to SQL, keeping care of single quotes", ()
{
expect(sqlString("ONE'TWO''THREE'''")).toEqual("'ONE''TWO''''THREE'''''''");
});
});
});
// TODO connection tests (ports/service running etc)
describe('SqlConnection methods', ()
{
beforeEach(() async
{
await conn.open();
});
afterEach(() async
{
await conn.close();
});
describe("execute()", ()
{
it("returns the number of rows effected", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE HasWebSite=1");
expect(n).toEqual(2);
});
it("does UPDATE commands correctly when not changing anything", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE HasWebSite=1");
expect(n).toEqual(2);
});
it("returns 0 when nothing done", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE 0=1");
expect(n).toEqual(0);
});
it("does UPDATE commands correctly", () async
{
var n = await conn.execute("UPDATE Customers SET Name='Bill' WHERE Name='Bob'");
expect(n).toEqual(1);
var n1 = await conn.queryValue("SELECT COUNT(*) FROM Customers WHERE Name='Bob'");
var n2 = await conn.queryValue("SELECT COUNT(*) FROM Customers WHERE Name='Bill'");
expect(n1).toEqual(0);
expect(n2).toEqual(1);
n = await conn.execute("UPDATE Customers SET Name='Bob' WHERE Name='Bill'"); // reverts back
expect(n).toEqual(1);
});
});
describe("queryValue()", ()
{
it("returns null when querying empty rows", () async
{
// no customers named 'Mark'
var n = await conn.queryValue("SELECT Name FROM Customers WHERE Name='Mark'");
expect(n,null);
});
it("returns an integer value from query", () async
{
// Mary's Age is 18
var age = await conn.queryValue("SELECT Age FROM Customers WHERE Name='Mary'");
expect(age,18);
});
it("returns a boolean from query", () async
{
// Mary has a web site
var bit = await conn.queryValue("SELECT HasWebSite FROM Customers WHERE Name='Mary'");
expect(bit,true);
});
it("returns a String from query", () async
{
// Bob does not have a website
var name = await conn.queryValue("SELECT Name FROM Customers WHERE HasWebSite=0");
expect(name,"Bob");
});
it("returns null when queried field is null", () async
{
// First customer does not have a date
var born = await conn.queryValue("SELECT Born FROM Customers");
expect(born,null);
});
it("returns a DateTime from query", () async
{
var tomsborn = await conn.queryValue("SELECT Born FROM Customers WHERE Name = 'Tom'");
expect(tomsborn is DateTime).toEqual(true);
expect(tomsborn).toEqual(new DateTime(1972,05,03));
});
});
describe("querySingle()", ()
{
it("returns null when querying empty rows", () async
{
// no customers named 'Mark'
var n = await conn.querySingle("SELECT Name FROM Customers WHERE Name='Mark'");
expect(n).toEqual(null);
});
it("returns a row from query", () async
{
// tom's row
var row = await conn.querySingle("SELECT * FROM Customers WHERE Name='Tom'");
expect(row is Map).toEqual(true);
expect(row).toEqual({ "Id": 2, "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) });
});
});
describe("query()", ()
{
it("returns an empty List when querying empty rows", () async
{
// no customers named 'Mark'
var q = await conn.query("SELECT Name FROM Customers WHERE Name='Mark'");
expect(q).toEqual([]);
});
it("returns rows from query", () async
{
var q = await conn.query("SELECT Name, Age, HasWebSite, Born FROM Customers ORDER BY Id");
expect(q is List).toEqual(true);
expect(q.length).toEqual(3);
expect(q).toEqual(
[
{ "Name": 'Bob' , "Age": 33, "HasWebSite": false, "Born": null },
{ "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) },
{ "Name": 'Mary', "Age": 18, "HasWebSite": true, "Born": null }
]);
});
});
describe("queryTable()", ()
{
it("when result is empty, returns no rows and filled column info", () async
{
// no customers named 'Mark'
var table = await conn.queryTable("SELECT Name FROM Customers WHERE Name='Mark'");
expect(table.rows.length).toEqual(0);
expect(table.columns.length).toEqual(2); // Primary key Id is always included
});
it("returns a full datased", () async
{
// no customers named 'Mark'
var table = await conn.queryTable("SELECT Id, Name, Age, HasWebSite, Born FROM Customers ORDER BY Id");
expect(table.tableName).toEqual("Customers");
expect(table.rows.length).toEqual(3);
expect(table.columns.length).toEqual(5);
expect(table.rows).toEqual(
[
{ "Id": 1, "Name": 'Bob' , "Age": 33, "HasWebSite": false, "Born": null , "_originalIndex": 0 },
{ "Id": 2, "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) , "_originalIndex": 1 },
{ "Id": 3, "Name": 'Mary', "Age": 18, "HasWebSite": true, "Born": null , "_originalIndex": 2 }
]);
});
});
});
}
library sql_server_socket;
import "dart:io";
import "dart:async";
import "dart:convert";
import 'dart:typed_data';
import "table.dart";
class SqlConnection {
late Socket _socket;
late StringBuffer _receiveBuffer;
late Completer _completer;
late bool _connected;
late String _address;
late int _port;
late String _connectionString;
SqlConnection(String connStr,
{String address: "localhost", int port: 10980}) {
_address = address;
_port = port;
_connected = false;
_connectionString = connStr;
}
/// tells if database is connected
bool get connected => _connected;
/// connects to sql server database using the specified connection string
Future<bool> open() async {
try {
this._socket = await Socket.connect(_address, _port);
//print("Connected to: ${_socket.remoteAddress.address}:${_socket.remotePort}");
} catch (ex) {
// throw "can't connect to ${_address}:${_port} -- $ex";
throw "can't connect to $_address:$_port -- $ex";
}
//Establish the onData, and onDone callbacks
_socket
.transform(utf8.decoder as StreamTransformer<Uint8List, dynamic>)
.listen(_receiveData, onError: _onError, onDone: _onDone);
Completer<bool> connectCompleter = new Completer();
// String json = JSON.encode({"type": "open", "text": _connectionString});
String json = jsonEncode({"type": "open", "text": _connectionString});
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _OkResult) {
_connected = true;
connectCompleter.complete(true);
} else if (res is _ErrorResult) {
_connected = false;
connectCompleter.completeError(res.error);
} else
throw "unknown response";
}).catchError((err) {
_connected = false;
connectCompleter.completeError(err);
});
return connectCompleter.future;
}
/// disconnects from sql server
Future<bool> close() {
if (!connected) throw "not connected";
Completer<bool> disconnectCompleter = new Completer();
String json = jsonEncode({"type": "close", "text": ""});
_sendCommand(json).then((risp) {
var res = _parseResult(risp);
if (res is _OkResult) {
_connected = false;
disconnectCompleter.complete(true);
} else if (res is _ErrorResult) {
disconnectCompleter.completeError(res.error);
} else
throw "unknown response";
}).catchError((err) {
disconnectCompleter.completeError(err);
});
return Future.value(disconnectCompleter.future);
}
/// launch a query on the database, returning a table
Future<Table> queryTable(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "table", "text": sql});
Completer<Table> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _TableResult) {
var tres = res;
Table tab = new Table(this, tres.tableName, tres.rows, tres.columns);
compl.complete(tab);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
Future<PostBackResponse> postBack(ChangeSet chg) {
if (!connected) throw "not connected";
String params = jsonEncode(chg.toEncodable());
String json = jsonEncode({"type": "postback", "text": params});
Completer<PostBackResponse> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _PostBackResult) {
var tres = res;
PostBackResponse resp = new PostBackResponse();
resp.idcolumn = tres.idcolumn;
resp.identities = tres.identities;
compl.complete(resp);
} else
throw "invalid postback response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning all rows
Future<List<Map<String, dynamic>>> query(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "query", "text": sql});
Completer<List<Map<String, dynamic>>> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult)
compl.complete(res.rows);
else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning the first rows only
Future<Map<String, dynamic>> querySingle(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "querysingle", "text": sql});
Completer<Map<String, dynamic>> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(null);
else
compl.complete(res.rows[0]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning the value from the first column of the first row
Future<dynamic> queryValue(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "queryvalue", "text": sql});
Completer compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(null);
else
compl.complete(res.rows[0]["value"]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// executes a sql command, returning the number of rows affected
Future<int> execute(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "execute", "text": sql});
Completer<int> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(-1);
else
compl.complete(res.rows[0]["rowsAffected"]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// formats and write a command to the socket
Future<String> _sendCommand(String command) {
// prepare buffer for response
_receiveBuffer = new StringBuffer();
Completer<String> _completer = new Completer();
String cmd = command.length.toString() + "\r\n" + command;
_socket.write(cmd);
return _completer.future;
}
void _onDone() {
//print("onDone()");
//socket.destroy();
}
void _onError(error) {
print("error occurred: $error");
}
/// receive data from socket and build a command string
///
/// client sends text-based commands with the format:
/// size_of_command_string + "\r\n" + command_string
void _receiveData(data) {
_receiveBuffer.write(data);
String content = _receiveBuffer.toString();
if (content.indexOf("\r\n") > 0) {
int x = content.indexOf("\r\n");
int len = int.parse(content.substring(0, x)); // size of command string
String cmd = content.substring(x + 2);
if (cmd.length == len) {
_completer.complete(cmd);
}
}
}
/// translates generic json result into a Result type
dynamic _parseResult(String json) {
Map result = jsonDecode(json);
if (result["type"] == "ok")
return new _OkResult("ok");
else if (result["type"] == "error")
return new _ErrorResult(result["error"]);
else if (result["type"] == "query")
return new _QueryResult(result["rows"], result["columns"]);
else if (result["type"] == "table")
return new _TableResult(
result["tablename"], result["rows"], result["columns"]);
else if (result["type"] == "postback")
return new _PostBackResult(result["idcolumn"], result["identities"]);
else
throw "unknown response";
}
}
class _ErrorResult {
late String error;
_ErrorResult(String error) {
this.error = error;
}
}
class _OkResult {
late String ok;
_OkResult(String ok) {
this.ok = ok;
}
}
class _QueryResult {
late List<Map<String, dynamic>> rows;
late Map<String, dynamic> columns;
_QueryResult(List<Map<String, dynamic>> rows, Map<String, dynamic> columns) {
this.rows = rows;
this.columns = columns;
// fix types
for (var fieldName in columns.keys) {
TypeFixer.fixColumn(rows, fieldName, columns[fieldName]);
}
}
}
class _TableResult {
late String tableName;
late List<Map<String, dynamic>> rows;
late List<Map<String, String>> columns;
_TableResult(String tableName, List<Map<String, dynamic>> rows,
List<Map<String, String>> columns) {
this.tableName = tableName;
this.rows = rows;
this.columns = columns;
}
}
class _PostBackResult {
late String idcolumn;
late List<int> identities;
_PostBackResult(String idcolumn, List<int> identities) {
this.idcolumn = idcolumn;
this.identities = identities;
}
}
/// translates a JSON encoded SQL type into a Dart type
class TypeFixer {
/// fix string data type coming from JSON into proper Dart data type
static void fixColumn(
List<Map<String, dynamic>> rows, String columnName, String columnType) {
if (columnType == "datetime") {
for (int t = 0; t < rows.length; t++) {
if (rows[t][columnName] != null)
rows[t][columnName] = DateTime.parse(rows[t][columnName]);
}
}
}
}
pubspec.yaml
name: sql_server_socket
version: 0.0.1
description: A minimal command-line application.
#author: <Antonino Porcino> <nino.porcino#gmail.com>
#homepage: https://github.com/nippur72/SqlServerSocket
environment:
sdk: ">=2.7.0 <3.0.0"
#dependencies:
# foo_bar: '>=1.0.0 <2.0.0'
dev_dependencies:
unittest: any
guinness: ">=1.3.0 <2.0.0"
I'm using Flutter Dart to develop an application, in that I'm trying to establish Sql connection with Sql server and application.
This is the link I referred for connection https://github.com/nippur72/SqlServerSocket .
While trying to add dependencies in pubspec.yaml, under dev_dependencies the version of guinness is not updating to the newer version(pub update). While clicking pub get i'm receiving this error,
Resolving dependencies...
Because sql_server_socket depends on guinness ^1.3.0 which doesn't match any versions, version solving failed.
Process finished with exit code 1
I have tried specifying the version manually and i know it doesn't work that way. So I used pub update, tried updating the whole flutter and dart version, yet receiving the same error.
Is there any other solution other than guinness? Or how can I get the actual guinness version. I have tried surfing thru internet for guinness versions but had no relevant result.
Please help me with this issue. I've been stuck with sql connection for past few days.
Thanks in advance!
Error message
You can use SQLite to store data locally and then use the package sql_conn 0.0.3 to do the insert/update operations on SQL Server.
I am going to try this suggestion myself this month, and will comment on my results.

Use array to add new entry in model in asp.net mvc

I'm using asp.net mvc 4 and Entity Framework 6 to make a website where I can store data in MSSQL database. I want to make a function where it'll make a copy of an entry with different id. I want to put those copied values in an array and push it to the model to make the back-end processing faster. But I'm not sure how to do it.
Here are my codes:
public ActionResult FlatCopy(FlManagement FlTable, int FlId = 0)
{
var getOwner = rentdb.OwnerRegs.Where(a => a.username == User.Identity.Name).FirstOrDefault();
var getId = getOwner.serial;
var getLimit = getOwner.limit;
var getPosted = getOwner.posted;
FlInfo model = FlTable.Flats;
if (ModelState.IsValid)
{
if (getLimit != 0)
{
try
{
getOwner.limit = getLimit - 1;
getOwner.posted = getPosted + 1;
var dbPost = rentdb.FlatInfoes.Where(p => p.serial == FlId).FirstOrDefault();
if (dbPost == null)
{
TempData["flat_edit_fail"] = "Error! Information update failed!";
return RedirectToAction("FlatManager", new { FlPanelId = "AllFl" });
}
model.flatno = "Copy of " + dbPost.flatno;
model.type = dbPost.type;
model.owner_id = getId;
model.t_id = 0;
model.t_name = "N/A";
model.t_phone = "N/A";
model.basic = dbPost.basic;
model.electric = dbPost.electric;
model.gas = dbPost.gas;
model.water = dbPost.water;
model.total = dbPost.total;
model.advancerent = dbPost.advancerent;
model.currency = dbPost.currency;
model.title = dbPost.title;
model.status = "N/A";
db.FlatInfoes.Add(model);
db.SaveChanges();
TempData["success"] = "Information Added Successfully!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
catch
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "You've reached your post limit!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
How can I put the values in an array and push the array in model to add a new entry?
You could detach the entity from the DbContext then re-add it to the EntityCollection.
rentdb.Entry(dbPost).State = EntityState.Detached;
rentdb.FlatInfoes.Add(dbPost);
solution 2:(is better)
var model = new FlInfo();
rentdb.FlatInfoes.Add(model);
var sourceValues = rentdb.Entry(dbPost).CurrentValues;
rentdb.Entry(model).CurrentValues.SetValues(sourceValues);
rentdb.SaveChanges();

Resources