WPF - I cannot start the app because of the connection exception that i'm getting - c#

System.InvalidOperationException: 'Timeout expired. The timeout
period elapsed prior to obtaining a connection from the pool. This
may have occurred because all pooled connections were in use and max
pool size was reached.'
Im trying to add existing username to a collection of errors and i started receiving this exception...
Im getting exception in this class:
public class UsersCollection: ObservableCollection<Users>
{
public static UsersCollection GetAllUserNames()
{
UsersCollection users = new UsersCollection();
Users user = null;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
conn.Open(); //I GET EXCEPTION ON THIS LINE.
SqlCommand command = new SqlCommand("SELECT UserName FROM Users", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
user = Users.GetUserNamesFromResultSet(reader);
users.Add(user);
}
}
}
return users;
}
}
Class with code that causes the exception:
public class Users : INotifyPropertyChanged, INotifyDataErrorInfo
{
private int _id;
private string _username;
private string _password;
private bool _isAdmin;
private Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
public string UserName
{
get { return _username; }
set
{
if (_username == value)
{
return;
}
_username = value;
List<string> errors = new List<string>();
bool valid = true;
if (value == null || UserName.Length < 5)
{
errors.Add("Username can not have less than 5 characters.");
SetErrors("UserName", errors);
valid = false;
}
UsersCollection collection = new UsersCollection();
collection = UsersCollection.GetAllUserNames();
for (int i = 0; i < collection.Count; i++)
{
if (UserName == (object)collection[i])
{
errors.Add("Username already exist.");
SetErrors("UserName", errors);
valid = false;
}
}
if (!Regex.Match(value, #"^\w+$").Success)
{
errors.Add("Username can only contain letters, numbers and underscore characters.");
SetErrors("UserName", errors);
valid = false;
}
if (valid)
{
ClearErrors("UserName");
}
OnPropertyChanged(new PropertyChangedEventArgs("UserName"));
}
private void SetErrors(string propertyName, List<string> propertyErrors)
{
errors.Remove(propertyName);
errors.Add(propertyName, propertyErrors);
if(ErrorsChanged != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
private void ClearErrors(string propertyName)
{
errors.Remove(propertyName);
if (ErrorsChanged != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
public static Users GetUserNamesFromResultSet(SqlDataReader reader)
{
Users user = new Users((string)reader["UserName"]);
return user;
}
I started receiving exception after i added these lines (I'm not shure if code would do as i wanted, i couldn't test it):
UsersCollection collection = new UsersCollection();
collection = UsersCollection.GetAllUserNames();
for (int i = 0; i < collection.Count; i++)
{
if (UserName == (object)collection[i])
{
errors.Add("Username already exist.");
SetErrors("UserName", errors);
valid = false;
}
}
How can i fix this?

what i understood from your question is that you are trying to connect to a pool and from his pool your trying to select a data from users table but sadly you ran into a problem with the pool because its reached max size or limit mmm if you are correct with the connection string try to make cmd.Timeout = 0; there will try reconnect again and again and again until you able to get into the pool.

Related

C# WebAPI Thread Aborting when Sharing Data Access Logic

I'm getting the following error on my C# Web API: "Exception thrown: 'System.Threading.ThreadAbortException' in System.Data.dll
Thread was being aborted". I have a long running process on one thread using my data access logic class to get and update records being process. Meanwhile a user submits another group to process which has need of the same data access logic class, thus resulting in the error. Here is a rough sketch of what I'm doing.
WebAPI Class:
public IHttpActionResult OkToProcess(string groupNameToProcess)
{
var logic = GetLogic();
//Gets All Unprocessed Records and Adds them to Blocking Queue
Task.Factory.StartNew(() => dataAccessLogic.LoadAndProcess(groupNameToProcess);
}
public IHttpActionResult AddToProcess(int recordIdToProcess)
{
StaticProcessingFactory.AddToQueue(recordIdToProcess);
}
StaticProcessingFactory
internal static ConcurrentDictionary<ApplicationEnvironment, Logic> correctors = new ConcurrentDictionary<ApplicationEnvironment, Logic>();
internal static BlockingCollection<CorrectionMessage> MessageQueue = new BlockingCollection<Message>(2000);
public void StartService(){
Task.Factory.StartNew(() => LoadService());
}
public void LoadService(){
var logic = GetLogic();
if(isFirstGroupOkToProcessAsPerTextFileLog())
logic.LoadAndProcess("FirstGroup");
if(isSeconddGroupOkToProcessAsPerTextFileLog())
logic.LoadAndProcess("SecondGroup");
}
public static GetLogic(){
var sqlConnectionFactory = Tools.GetSqlConnectionFactory();
string environment = ConfigurationManager.AppSettings["DefaultApplicationEnvironment"];
ApplicationEnvironment applicationEnvironment =
ApplicationEnvironmentExtensions.ToApplicationEnvironment(environment);
return correctors.GetOrAdd(applicationEnvironment, new Logic(sqlConnectionFactory ));
}
public static void AddToQueue(Message message, bool completeAdding = true)
{
if (MessageQueue.IsAddingCompleted)
MessageQueue = new BlockingCollection<Message>();
if (completeAdding && message.ProcessImmediately)
StartQueue(message);
else
MessageQueue.Add(message);
}
public static void StartQueue(Message message = null)
{
if (message != null)
{
if(!string.IsNullOrEmpty(message.ID))
MessageQueue.Add(message);
Logic logic = GetLogic(message.Environment);
try
{
var messages = MessageQueue.TakeWhile(x => logic.IsPartOfGroup(x.GroupName, message.GroupName));
if (messages.Count() > 0)
MessageQueue.CompleteAdding();
int i = 0;
foreach (var msg in messages)
{
i++;
Process(msg);
}
}
catch (InvalidOperationException) { MessageQueue.CompleteAdding(); }
}
}
public static void Process(Message message)
{
Var logic = GetLogic(message.Environment);
var record = logic.GetRecord(message.ID);
record.Status = Status.Processed;
logic.Save(record);
}
Logic Class
private readonly DataAccess DataAccess;
public Logic(SqlConnectionFactory factory)
{
DataAccess = new DataAcess(factory);
}
public void LoadAndProcess(string groupName)
{
var groups = DataAccess.GetGroups();
var records = DataAccess.GetRecordsReadyToProcess(groups);
for(int i = 0; i < records.Count; i++)
{
Message message = new Message();
message.Enviornment = environment.ToString();
message.ID = records[i].ID;
message.User = user;
message.Group = groupName;
message.ProcessImmediately = true;
StaticProcessingFactory.AddToQueue(message, i + 1 == records.Count);
}
}
Any ideas how I might ensure that all traffic from all threads have access to the Data Access Logic without threads being systematically aborted?

I am getting null pointer exception in asp.net application

I am debugging an asp.net application. It works flawlessly in test environment, however, I am getting null reference exception in real server. I am using ninject. The problem arose from ninject I suppose.Here is the problematic code fragment:
public partial class PersonelAylikRapor : MasterClass
{
protected void btnSorgula_Click(object sender, EventArgs e)
{
//other codes ommited for brevity
DateTime baslangicTarihi = DateTime.MinValue;
//arac is null here.
baslangicTarihi = this.arac.CevirDateTimea("01." + ddlAy.SelectedValue + "." + ddlYil.SelectedValue);
}
}
the variable arac should have been solved in MasterClass, since it is the father class, so I do not check null reference issue.
MasterClass is the place that I set the ninject kernel. Here is the content of the MasterClass:
public class MasterClass : System.Web.UI.Page
{
IKernel ninjectKernel = null;
private bool cekirdekKurulduMu = false;
public IPersonelIsKurali personelik = null;
public IAraclarTaha arac = null;
public ITurnikePersonelIsKurali turnikepersonelik = null;
public IPersonelBirimlerIsKurali personelbirimlerik = null;
public ITurnikeIslemlerIsKurali turnikeIsKurali = null;
public IPersonelIliskilendir personelilisiklendirik = null;
public IBirimlerIsKurali birimlerik = null;
public IPersonelIzinIsKurali personelizinik = null;
public IServisIsKurali servisIsKurali = null;
public FonksiyonSonuc fs = null;
public List<PersonelKunye> listpersonelkunye = null;
public List<uint> listgorebilecegipersonelid = null;
public MasterClass()
{
}
protected override void OnPreInit(EventArgs e)
{
try
{
base.OnPreInit(e);
if (this.cekirdekKurulduMu == false)
{
this.cekirdekKurulduMu = true;
this.ninjectKernel = new StandardKernel();
this.ninjectCekirdegiKur(this.ninjectKernel);
this.DegiskenlereAta();
}
}
catch (Exception ex)
{
IAraclarTaha arac = new AraclarTaha();
FonksiyonSonuc fs = new FonksiyonSonuc(true);
fs = arac.HatayiVeritabaninaYaz(ex, OrmanSuTypes.Enums.HataCiddiyetiEnum.OLUMCUL);
if (fs.fonksiyonBasariDurumu == false)
{
throw ex;
}
}
}
private void ninjectCekirdegiKur(IKernel ninjectKernel)
{
this.ninjectKernel = new StandardKernel();
this.ninjectKernel.Bind<IPersonelBirimlerIsKurali>().To<PersonelBirimlerIsKurali>();
this.ninjectKernel.Bind<IPersonelIzinIsKurali>().To<PersonelIzinIsKurali>();
this.ninjectKernel.Bind<IPersonelIsKurali>().To<PersonelIsKurali>();
this.ninjectKernel.Bind<IAraclarTaha>().To<AraclarTaha>().WithConstructorArgument("debugMode", Araclar.DebugModdaMi());
this.ninjectKernel.Bind<ITurnikeIslemlerIsKurali>().To<TurnikeIslemlerIsKurali>();
this.ninjectKernel.Bind<IBirimlerIsKurali>().To<BirimlerIsKurali>();
this.ninjectKernel.Bind<IPersonelIliskilendir>().To<PersonelIiskilendirIsKurali>();
this.ninjectKernel.Bind<ITurnikePersonelIsKurali>().To<TurnikePersonelIsKurali>();
this.ninjectKernel.Bind<IServisIsKurali>().To<ServisIsKurali>();
}
public void DegiskenlereAta()
{
if (this.arac == null)
{
this.arac = this.ninjectKernel.Get<IAraclarTaha>();
}
if (this.personelik == null)
{
this.personelik = this.ninjectKernel.Get<IPersonelIsKurali>();
}
if (this.turnikepersonelik == null)
{
this.turnikepersonelik = this.ninjectKernel.Get<ITurnikePersonelIsKurali>();
}
if (this.personelbirimlerik == null)
{
this.personelbirimlerik = this.ninjectKernel.Get<IPersonelBirimlerIsKurali>();
}
if (this.turnikeIsKurali == null)
{
this.turnikeIsKurali = this.ninjectKernel.Get<ITurnikeIslemlerIsKurali>();
}
if (this.personelilisiklendirik == null)
{
this.personelilisiklendirik = this.ninjectKernel.Get<IPersonelIliskilendir>();
}
if (this.birimlerik == null)
{
this.birimlerik = this.ninjectKernel.Get<IBirimlerIsKurali>();
}
if (this.personelizinik == null)
{
this.personelizinik = this.ninjectKernel.Get<IPersonelIzinIsKurali>();
}
if (this.fs == null)
{
this.fs = new FonksiyonSonuc(true);
}
if (this.servisIsKurali == null)
{
this.servisIsKurali = this.ninjectKernel.Get<IServisIsKurali>();
}
}
}
What is wrong with it? Thanks in advance.
Edit-1: Here is the visual explanatory of the error:
I have just solve that problem. You can not set your ninject kernel in such manner. Implementing ninject kernel in asp.net web forms are expressed here:
How can I implement Ninject or DI on asp.net Web Forms?

I am trying to access data in a C# packet I've created, however I keep getting null as a response. What am I doing wrong?

Okay, so I'm working with custom network code for pretty much the first time. I have a packet created to transfer some game information back and forth, however beyond the initial content if I try to access some of the commands, I get "null" - though on the server side, it's showing as properly populated.
I have a feeling that this has to do with the setup in receiving the data. The code for the packet follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum DataIdentifier
{
Message,
Command,
LogIn,
LogOut,
Null
}
public class Packet
{
private DataIdentifier dataIdentifier;
private string name;
private string player;
private string playerData;
private string message;
private string command;
private string x;
private string y;
private string z;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Player
{
get
{
return player;
}
set
{
player = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string Command
{
get
{
return command;
}
set
{
command = value;
}
}
public DataIdentifier DataIdentifier
{
get
{
return dataIdentifier;
}
set
{
dataIdentifier = value;
}
}
public string PlayerData
{
get
{
return playerData;
}
set
{
playerData = value;
}
}
public string X
{
get
{
return x;
}
set
{
x = value;
}
}
public string Y
{
get
{
return y;
}
set
{
y = value;
}
}
public string Z
{
get
{
return z;
}
set
{
z = value;
}
}
public Packet()
{
this.DataIdentifier = DataIdentifier.Null;
this.message = null;
this.name = null;
this.player = null;
this.playerData = null;
this.x = null;
this.y = null;
this.z = null;
this.command = null;
}
public Packet(byte[] dataStream)
{
// Read the data identifier from the beginning of the stream (4 bytes)
this.DataIdentifier = (DataIdentifier)BitConverter.ToInt32(dataStream, 0);
// Read the length of the name (4 bytes)
int nameLength = BitConverter.ToInt32(dataStream, 4);
// Read the length of the message (4 bytes)
int msgLength = BitConverter.ToInt32(dataStream, 8);
// Read the name field
if (nameLength > 0)
this.name = Encoding.UTF8.GetString(dataStream, 12, nameLength);
else
this.name = null;
// Read the message field
if (msgLength > 0)
this.message = Encoding.UTF8.GetString(dataStream, 12 + nameLength, msgLength);
else
this.message = null;
}
public byte[] GetDataStream()
{
List<byte> dataStream = new List<byte>();
// Add the dataIdentifier
dataStream.AddRange(BitConverter.GetBytes((int)this.DataIdentifier));
// Add the name length
if (this.name != null)
dataStream.AddRange(BitConverter.GetBytes(this.name.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the message length
if (this.message != null)
dataStream.AddRange(BitConverter.GetBytes(this.message.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the name
if (this.name != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.name));
// Add the message
if (this.message != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.message));
if (this.playerData != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.playerData));
}
if (this.command != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.command));
}
if (this.x != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.x));
}
if (this.y != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.y));
}
if (this.z != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.z));
}
return dataStream.ToArray();
}
}
This is how the packet is recieved:
// Receive all data
this.clientSocket.EndReceive(AR);
// Initialise a packet object to store the received data
Packet receivedData = new Packet(this.dataStream);
// Evaulate command played
if (PacketDelegate != null)
{
PacketDelegate(receivedData);
}
// Reset data stream
this.dataStream = new byte[8142];
// Continue listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveCallback), null);
And this is the delegate function responsible for handling a packet:
public void RecievePacket(Packet Communication)
{
// Check and manipulate the contents of the packet here //
}
I have confirmed that I can get name, DataIdentifier, and Message, but it's the additional information I've added to the packet itself - player/data, command, x,y,z, I can't seem to get.
My thought is that the problem exists in establishing Packet(byte[] dataStream). However, I'm not quite sure how to calculate or add the additional variables to this. Can anyone give me some tips on how to do so?

Reduce Multiple Calls To Database

I have a code a base that iterates through a list of records and does the follwing
'select * from Table to see if fields exist
then later in the interation
'select * from Table to retreive some data
then farther down in the interation
select field1, field2 from Table to get certain pieces of information
I need to do all of these functions for each record. Would the process speed up if I called the query once for each record and hold the data in a datatable and retreive what I need from there? Or is there another more efficient way to not have to make 3 db calls to the same table which will speed up the process?
You can cache query data to System.Data.DataTable. To simplify things I has written CMyDynaset class, which populates DataTable with data from DB. Here how to use it for example with MySQL:
using System;
using System.Data.Common;
using MySql.Data.MySqlClient;
namesapce MyProg
{
class Program
{
private const string strMyConnection = "Host=localhost;Database=mydb;User Id=myuser;Password=mypsw";
static void Main(string[] args)
{
using (MySqlConnection myConnection = new MySqlConnection(strMyConnection))
{
using (MyDb.CMyDynaset dyn = new MyDb.CMyDynaset(myConnection, MySqlClientFactory.Instance))
{
// populate dyn.Table (System.Data.DataTable)
dyn.Init("select * from Table");
dyn.Load();
// access fields
foreach (DataColumn column in dyn.Table.Columns)
{
// ...
}
// get data
long nCountAll = dyn.Table.Rows.Count; // rows count
foreach (DataRow row in dyn.Table.Rows)
{
Object val1 = row[1]; // acess by index
Object val2 = row["id"]; // acess by name
// ...
}
// update data
dyn.Table.Rows[0]["name"] = "ABC";
dyn.Update();
}
}
}
}
}
CMyDynaset class (CMyDynaset.cs):
// CMyDynaset.cs
using System;
using System.Data.Common;
namespace MyDb
{
/// <summary>
/// Summary description for CMyDynaset.
/// </summary>
public class CMyDynaset : IDisposable
{
public System.Data.DataTable Table = null;
// private
private DbConnection myConnection = null;
private DbProviderFactory myFactory = null;
private DbDataAdapter dataAdap = null;
private DbCommandBuilder cmdBld = null;
private bool bIsSchema = false;
public CMyDynaset(DbConnection conn, DbProviderFactory factory)
{
this.myConnection = conn;
this.myFactory = factory;
}
#region IDisposable Members
public void Dispose()
{
if (this.Table != null)
{
this.Table.Dispose();
this.Table = null;
}
if (this.cmdBld != null)
{
this.cmdBld.Dispose();
this.cmdBld = null;
}
if (this.dataAdap != null)
{
this.dataAdap.Dispose();
this.dataAdap = null;
}
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
// Init
public void Init(string strSelect)
{
DbCommand cmdSel = this.myConnection.CreateCommand();
cmdSel.CommandText = strSelect;
this.dataAdap = this.myFactory.CreateDataAdapter();
this.dataAdap.SelectCommand = cmdSel;
this.cmdBld = this.myFactory.CreateCommandBuilder();
this.cmdBld.DataAdapter = this.dataAdap;
this.Table = new System.Data.DataTable();
// schema
this.bIsSchema = false;
}
public void AddParameter(string name, object value)
{
DbParameter param = this.dataAdap.SelectCommand.CreateParameter();
param.ParameterName = name;
param.Value = value;
this.dataAdap.SelectCommand.Parameters.Add(param);
}
public void AddParameter(DbParameter param)
{
this.dataAdap.SelectCommand.Parameters.Add(param);
}
// Open, Close
private void Open(ref bool bClose)
{
if (this.myConnection.State == System.Data.ConnectionState.Closed)
{
this.myConnection.Open();
bClose = true;
}
if (!this.bIsSchema)
{ // schema
this.dataAdap.FillSchema(this.Table, System.Data.SchemaType.Mapped);
this.bIsSchema = true;
}
}
private void Close(bool bClose)
{
if (bClose)
this.myConnection.Close();
}
// Load, Update
public void Load()
{
bool bClose = false;
try
{
this.Table.Clear();
this.Open(ref bClose);
this.dataAdap.Fill(this.Table);
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
this.Close(bClose);
}
}
public void Update()
{
bool bClose = false;
try
{
this.Open(ref bClose);
this.dataAdap.Update(this.Table);
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
this.Close(bClose);
}
}
}
}

Refresh Application Automatically When Data changed in SQL Server

I use SQL Server and I have 3 Application servers. When a table in my database have changed I need to those application servers refresh there local cached data. I use a trigger to known change and send a message via Service broker queue. Then I create a stored procedure and assign it to activate stored procedure of my queue, In this stored procedure I receive message, but I don't know How should I call refresh method in my application.
I had similar issue but this code resolved the issue :
public class QueryNotification
{
public DataSet DataToWatch { get; set; }
public SqlConnection Connection { get; set; }
public SqlCommand Command { get; set; }
public string GetSQL()
{
return "SELECT * From YourTable";
}
public string GetConnection()
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
public bool CanRequestNotifications()
{
try
{
var perm = new SqlClientPermission(PermissionState.Unrestricted);
perm.Demand();
return true;
}
catch
{
return false;
}
}
public void GetData()
{
DataToWatch.Clear();
Command.Notification = null;
var dependency = new SqlDependency(Command);
dependency.OnChange += dependency_OnChange;
using (var adapter = new SqlDataAdapter(Command))
{
adapter.Fill(DataToWatch, "YourTableName");
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
var i = (ISynchronizeInvoke)sender;
if (i.InvokeRequired)
{
var tempDelegate = new OnChangeEventHandler(dependency_OnChange);
object[] args = { sender, e };
i.BeginInvoke(tempDelegate, args);
return;
}
var dependency = (SqlDependency)sender;
dependency.OnChange -= dependency_OnChange;
GetData();
}
}
Update:
Check for permission:
public bool CanRequestNotifications()
{
try
{
var perm = new SqlClientPermission(PermissionState.Unrestricted);
perm.Demand();
return true;
}
catch
{
return false;
}
}
For Instance in your window load:
if (!_queryNotification.CanRequestNotifications())
{
MessageBox.Show("ERROR:Cannot Connect To Database");
}
SqlDependency.Stop(_queryNotification.GetConnection());
SqlDependency.Start(_queryNotification.GetConnection());
if (_queryNotification.Connection == null)
{
_queryNotification.Connection = new SqlConnection(_queryNotification.GetConnection());
}
if (_queryNotification.Command == null)
{
_queryNotification.Command = new SqlCommand(_queryNotification.GetSQL(),
_queryNotification.Connection);
}
if (_queryNotification.DataToWatch == null)
{
_queryNotification.DataToWatch = new DataSet();
}
GetData();
You should look at using the SqlDependency class.
More information at: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency(v=vs.110).aspx
I can suggest you to try solving the problem using TCP. Each app listens to a port and when another app updates the db it sends a message to the other apps saying they need to refresh.
Hope that was a good idea.

Categories