I'm working on some code that executes MDX queries against sql server analysis service. The MDX query is being executed twice on the same thread and I have no idea why. The query should only execute once
Below is some of the code. can anyone help please.
private void Start_QueryWorkers()
{
foreach (QueryThread th in _QueryWorkers)
{
SSASQuery q = new SSASQuery();
q.QueryText = "SELECT NON EMPTY { [Measures].[count] } ON COLUMNS FROM [cube]";
q.queryThread = th;
th.WorkerThread.RunWorkerAsync(q);
}
}
private void QueryWorkerThread_DoWork(object sender, DoWorkEventArgs e)
{
SSASQuery q = e.Argument as SSASQuery;
OleDbCommand cmd = new OleDbCommand(q.QueryText, q.queryThread.conn);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Close();
}
private void btnStartTest_Click(object sender, EventArgs e)
{
string strConnString = "Provider=MSOLAP;Data Source=SRV001" + ";Initial Catalog=Cube_2015" + ";";
_QueryWorkers.Clear();
{
QueryThread thread = new QueryThread(strConnString);
thread.WorkerThread = new BackgroundWorker();
thread.WorkerThread.DoWork += new DoWorkEventHandler(this.QueryWorkerThread_DoWork);
_QueryWorkers.Add(thread);
}
Start_QueryWorkers();
}
}
class SSASQuery
{
public string QueryText { get; set; }
public QueryThread queryThread { get; set; }
}
class QueryThread
{
public QueryThread(string connString)
{
this.connString = connString;
conn = new OleDbConnection(connString);
conn.Open();
queryList = new SortedList();
}
public SortedList queryList { get; set; }
public string threadName { get; set; }
public string connString { get; set; }
public OleDbConnection conn;
public BackgroundWorker WorkerThread { get; set; }
}
}
solved. code was ok, it was a problem in the connection string execting the query twice
Related
I have text boxes to search for data, and 6 text boxes to display data if the data I am looking for is found. I'm trying to use an object class to make the code in the form look a little neat. the class is named ClsSearch. This is the class code snippet:
public string Name { get; set; }
public string txtCode { get; set; }
public string txtBarcode { get; set; }
public string txtUnit { get; set; }
public string txtQty { get; set; }
public string txtCost_price { get; set; }
public string txtSales_price { get; set; }
string mainconn = ConfigurationManager.ConnectionStrings["DbLearn"].ConnectionString;
public void X001_TextChanged()
{
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
string sqlquery = "SELECT * FROM tb_stock_product WHERE Item_Name='" + Name + "'";
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
mysqlconn.Open();
MySqlDataReader sdr;
sdr = sqlcmd.ExecuteReader();
if (sdr.Read())
{
txtCode = sdr.GetString("Code");
txtBarcode = sdr.GetString("Barcode");
txtUnit = sdr.GetString("Unit");
txtQty = sdr.GetDouble("Qty").ToString();
txtCost_price = sdr.GetInt32("Cost_price").ToString();
txtSales_price = sdr.GetInt32("Sales_price").ToString();
}
mysqlconn.Close();
then I tried calling the class in the form, exactly when the button was pressed, and this is the code:
private void X_001_Click(object sender, EventArgs e)
{
Connection_Frm_Ordering load = new Connection_Frm_Ordering();
load.X001_TextChanged();
load.Name = X_001.Text;
load.txtCode = X_002.Text;
load.txtBarcode = X_003.Text;
load.txtUnit = X_004.Text;
load.txtQty = X_005.Text;
load.txtCost_price = X_006.Text;
load.txtSales_price = X_007.Text;
}
but the code i made is not working.. can anyone help me where is the error ? sorry if this code might be messy, I'm still learning :)
I have this collection as seen in the code below and I am trying to execute the InserData function to insert the data form the collection to my SQL DB table in the Button_Click_1 event and cannot make it work. Any help?
The code takes data from form fields and adds to the Collection. Once the addition is complete and the user is done adding I want the entire collection written to a SQL data table.
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
// code to add from control data to list
ObservableCollection<LotData> lot = new ObservableCollection<LotData>();
private ObservableCollection<LotData> LoadCollectionData()
{
// List<LotData> lot = new List<LotData>();
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
return lot;
}
//button to add list data to datagrid on form
public void Button_Click(object sender, RoutedEventArgs e)
{
gridLotData.ItemsSource = LoadCollectionData();
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
//send data from DataGrid to database
{
InserData(LotData);
}
public void InserData(LotData lot)
{
string strConn = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Matthew\\QCast.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(strConn);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT into LotData Values (#LotNum)";
cmd.Connection = con
cmd.Parameters.AddWithValue("#LotNum", lot.Lot);
cmd.ExecuteNonQuery();
con.Close();
}
I think you've got a few things in the wrong place and you're recreating the ObservableCollection. You need to iterate over this to add all items to the DB:
private const string strConn = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Matthew\\QCast.mdf;Integrated Security=True;Connect Timeout=30";
private ObservableCollection<LotData> lot = new ObservableCollection<LotData>();
public Window1()
{
InitializeComponent();
// Bind ItemsSource once
gridLotData.ItemsSource = lot;
}
public void AddDataToGrid_Click(object sender, RoutedEventArgs e)
{
// Read data from form and add to collection
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
// Clear entry fields
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
private void WriteCollectionToDb_Click(object sender, RoutedEventArgs e)
{
using (var conn = new SqlConnection(strConn))
{
conn.Open();
try
{
foreach (var lotData in lot)
{
using (var command = new SqlCommand("INSERT into LotData Values (#LotNum)", conn))
{
command.Parameters.AddWithValue("LotNum", lotData.Lot);
command.ExecuteNonQuery();
}
}
}
finally
{
conn.Close();
}
}
}
In InserData, you have to iterate through all the items in the collection and then insert into DB
I am trying to write login app.
My problem is that Service gives me ArrayOfXElement instead of an object.
And I do not know how to get to this object.
Here is the code:
StartPage.xaml.cs
using (...);
namespace MyFirstProject
{
public sealed partial class StartPage : Page
{
ServiceReference1.Service1Client MyService;
public StartPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MyService = new ServiceReference1.Service1Client();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.GetSinglePassCmdResponse h = MyService.GetSinglePassCmdAsync(new ServiceReference1.Pass { nickName = tBoxNick_log.Text }).Result;
Now I thought that in h I have object and I can do smth like this:
testBlock.Text = "nickname: " + h.nickname + " password: " + h.pass;
}}}
but I got error that GetSinglePassCmdResponse does not contain a definition for 'nickname'
IService1.cs
[OperationContract]
Pass GetSinglePassCmd(Pass Pass);
[DataContract]
public partial class Pass
{
[DataMember]
public string nickName { get; set; }
[DataMember]
public string password { get; set; }
[DataMember]
public Nullable<System.DateTime> lastLogDate { get; set; }
Service1.svc
public Pass GetSinglePassCmd(Pass Pass)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Passwords WHERE nickName=#nickName", con);
cmd.Parameters.AddWithValue("#nickName", Passwords.nickName);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
Pass pass = new Pass();
int i = 0;
if (ds.Tables[0].Rows.Count > 0)
{
//assign dataset values to array
pass.nickName = ds.Tables[0].Rows[i]["nickName"].ToString();
pass.password = ds.Tables[0].Rows[i]["password"].ToString();
pass.lastLogDate = DateTime.Parse(ds.Tables[0].Rows[i]["lastLogDate"].ToString());
}
else pass = null;
return pass;
}
And in MyFirstProject->ServiceReferences->ServiceReference1->Reference.cs->GetSinglePassCmdResponse I got
public partial class GetSinglePassCmdResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult;
public GetSinglePassCmdResponse() {
}
public GetSinglePassCmdResponse(MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult) {
this.GetSinglePassCmdResult = GetSinglePassCmdResult;
}
}
Could anyone help me please... ?
PS I have also tried this:
testBlock.Text = "nickname: " + h.GetSinglePassCmdResult.nickname + " password: " + h.GetSinglePassCmdResult.pass;
Using Recursion I Want to Display the list of Contents to the datagridview in c# winforms.I tried by the below But as a result in datagridview Only Parent values displaying no Child Values Displayed
public class PageItem
{
public int Id { get; set; }
public int ParentId { get; set; }
public string MenuText { get; set; }
public List<PageItem> Childs { get; set; }
}
Conditions:-
public List<PageItem> GetPageItems()
{
List<PageItem> pageItems = new List<PageItem>();
SqlCeConnection conn = new SqlCeConnection(#"Data
Source=D:\database\Employee.mdf;");
SqlCeCommand cmd = new SqlCeCommand("SELECT Id, ParentId, MenuTitle
FROM Page", conn);
conn.Open();
SqlCeDataReader rdr = cmd.ExecuteReader();
var allItems = new List<PageItem>();
while (rdr.Read())
{
var item = (new PageItem()
{
Id = Convert.ToInt32(rdr["Id"]),
ParentId = Convert.ToInt32(rdr["ParentId"]),
MenuText = rdr["MenuTitle"].ToString()
});
allItems.Add(item);
var parent = allItems.Where(pi => pi.Id == item.ParentId).SingleOrDefault();
if (parent == null)
{
pageItems.Add(item);
}
else
{
if (parent.Childs == null)
parent.Childs = new List<PageItem>();
parent.Childs.Add(item);
}
}
rdr.Close();
conn.Close();
return pageItems;
}
Form Load:-
private void Form1_Load(object sender, EventArgs e)
{
GetPageItems();
this.dataGridView1.DataSource = GetPageItems();
this.comboBox1.DataSource = GetPageItems();
this.comboBox1.DisplayMember = "MenuText";
this.comboBox1.ValueMember = "ParentId";
}
From the above code I got an output like this:-
parent 0
parent 1
parent 2
parent 3
I Need an Output Like this:-
Parent 0
Child 1
Child 2
Child 3
Child 3.1
Child 3.2
Child 3.3
Parent 1
Parent 2
Parent 3
Thank You..
Finally I Got Answer For the Above Question Using Recursion .If Anybody Needs make Use of it Thank You:-
public class Student
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Title { get; set; }
}
public class Parent
{
public int pID { get; set; }
public int pParentID { get; set; }
public string pTitle { get; set; }
}
public class OutPut
{
public int mID { get; set; }
public int mParentID { get; set; }
public string mTitle { get; set; }
}
public class SubOutPut
{
public int SubsmID { get; set; }
public int SubsmParentID { get; set; }
public string SubsmTitle { get; set; }
}
Form Load
public static List<SubOutPut> ChildList = new List<SubOutPut>();
private void Form3_Load(object sender, EventArgs e)
{
List<Student> std = loaddataFull();
List<Parent> prnt = loaddataParent();
List<OutPut> MenuItems = new List<OutPut>();
foreach (Parent id in prnt)
{
int pid=Convert.ToInt32(id.pID);
//Adding Parent Values to the List
List<SubOutPut> SubMenuItems = new List<SubOutPut>();
MenuItems.Add(new OutPut()
{
mID=Convert.ToInt32(id.pID),
mParentID=Convert.ToInt32(id.pParentID),
mTitle=Convert.ToString(id.pTitle),
});
SubMenuItems = GetChildrens(pid);
foreach (SubOutPut Add in SubMenuItems)
{
MenuItems.Add(new OutPut()
{
mID = Convert.ToInt32(Add.SubsmID),
mParentID = Convert.ToInt32(Add.SubsmParentID),
mTitle = Convert.ToString(Add.SubsmTitle)
});
}
SubMenuItems.Clear();
}
dataGridView1.DataSource = MenuItems;
foreach (var item in MenuItems)
{
listView1.Items.Add(item.mID.ToString());
listView1.Items.Add(item.mParentID.ToString());
listView1.Items.Add(item.mTitle.ToString());
listView1.View = View.Tile;
}
dataGridView2.DataSource = loaddataParent();
}
Loading all datas from database
public List<Student> loaddataFull()
{
List<Student> student = new List<Student>();
SqlConnection conn = new SqlConnection(#"Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=true");
SqlCommand cmd = new SqlCommand("select * from testing", conn);
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
student.Add(new Student()
{
ID = dr.GetInt32(dr.GetOrdinal("id")),
ParentID = dr.GetInt32(dr.GetOrdinal("pid")),
Title = dr.GetString(dr.GetOrdinal("title"))
});
}
dr.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return student;
}
Load Only The Parent Values:-
public List<Parent> loaddataParent()
{
List<Parent> parent = new List<Parent>();
SqlConnection conn = new SqlConnection(#"Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=true");
SqlCommand cmd = new SqlCommand("select * from testing where pid=0", conn);
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
parent.Add(new Parent()
{
pID = dr.GetInt32(dr.GetOrdinal("id")),
pParentID = dr.GetInt32(dr.GetOrdinal("pid")),
pTitle = dr.GetString(dr.GetOrdinal("title"))
});
}
dr.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return parent;
}
And Here Comes The Recursion Method:-
public string gg = " ";
public List<SubOutPut> GetChildrens(int ID)
{
List<Student> std = loaddataFull();
foreach (Student Child in std)
{
if (Child.ParentID == ID)
{
ChildList.Add(new SubOutPut()
{
SubsmID = Convert.ToInt32(Child.ID),
SubsmParentID = Convert.ToInt32(Child.ParentID),
SubsmTitle = Convert.ToString(gg + Child.Title)
});
gg = gg+gg;
GetChildrens(Child.ID);
gg = " ";
}
}
return ChildList;
}
Thank You:---
DataBase Layer...................
public static void AddEnrollment(StudentScore enrollment)
{
SqlConnection conn = MyDB.GetConnection();
string insertStm = "insert into EnrollmentTable (StudentID,CourseID,DateEnrolled,Score) values (#StudentID,#CourseID,#DateEnrolled,#Score)";
SqlCommand insertComm = new SqlCommand(insertStm, conn);
insertComm.Parameters.AddWithValue("#StudentID", enrollment.EnrollmentData.StudentData.StudentID);
insertComm.Parameters.AddWithValue("#CourseID", enrollment.EnrollmentData.CourseData.CourseID);
insertComm.Parameters.AddWithValue("#DateEnrolled", enrollment.EnrollmentData.DOE);
insertComm.Parameters.AddWithValue("#Score", enrollment.Score);
try
{
conn.Open();
insertComm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
throw sqlex;
}
finally
{
conn.Close();
}
Business Layer...............
public class StudentScore
{
public Enrollment EnrollmentData { get; set; }
public int Score { get; set; }
public StudentScore()
{
}
public StudentScore(Enrollment aEnrollmentData, int aScore)
{
EnrollmentData = aEnrollmentData;
Score = aScore;
}
}
Presentation Layer..................
private void button5_Click(object sender, EventArgs e)
{
StudentScore enrollment = new StudentScore();
enrollment.EnrollmentData.StudentData.StudentID = comboBox1.SelectedValue.ToString();
enrollment.EnrollmentData.CourseData.CourseID = comboBox2.SelectedValue.ToString();
enrollment.EnrollmentData.DOE = DateTime.Now;
EnrollmentDB.AddEnrollment(enrollment);
MessageBox.Show("Student is enrolled this course.");
}
It show me this error
Exception : enrollment.EnrollmentData.StudentData.StudentID =
comboBox1.SelectedValue.ToString();
Please help me how do I fix it?
enrollment.EnrollmentData has not been initialized. In the absence of further details, change
StudentScore enrollment = new StudentScore();
to
StudentScore enrollment = new StudentScore(new Enrollment(), 0);