|
You'll need to add each value from the array as a separate parameter:
string[] ids = { "user1", "user2", "user3" };
using (SqlCommand cmd = con.CreateCommand())
{
StringBuilder commandText = new StringBuilder();
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
commandText.Append("SELECT COUNT(*) FROM xyz WHERE id IN (");
for (int index = 0; index < ids.Length; index++)
{
if (index != 0) commandText.Append(", ");
string name = string.Format(provider, "@P{0:D}", index);
cmd.Parameters.AddWithValue(name, ids[index]);
commandText.Append(name);
}
commandText.Append(')');
cmd.CommandText = commandText.ToString();
...
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hey,
I need some help with a program. The task is: I have 2n points in a list. I want to pair every points in the list by drawing n lines, in such a way that the sum of the lines distances is minimum. After some searches, I tried an implententation with the closest-pair algorithm, but that not really fulfill's the task. The sum can be smaller because of my last pair of "closest-points". So now I kinda have no idea how proceed with this, or what other idea should I consider to implement at all. Here is my implementation (which doesn't fulfill's the task):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Apropiere_Puncte
{
public partial class Form1 : Form
{
List<PointF> points = new List<PointF>();
public Form1()
{
InitializeComponent();
Random r = new Random();
for (int i = 0; i < 20; i++)
{
PointF p = new PointF(r.Next() % this.Size.Width - 20, r.Next() % this.Size.Height - 20);
if (p.X < 20)
p.X = 20;
if (p.Y < 20)
p.Y = 20;
points.Add(p);
}
}
public class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y);
}
}
public static Segment Closest_BruteForce(List<PointF> points)
{
int n = points.Count;
var result = Enumerable.Range(0, n - 1)
.SelectMany(i => Enumerable.Range(i + 1, n - (i + 1))
.Select(j => new Segment(points[i], points[j])))
.OrderBy(seg => seg.LengthSquared())
.First();
return result;
}
public static Segment MyClosestDivide(List<PointF> points)
{
return MyClosestRec(points.OrderBy(p => p.X).ToList());
}
private static Segment MyClosestRec(List<PointF> pointsByX)
{
int count = pointsByX.Count;
if (count <= 4)
return Closest_BruteForce(pointsByX);
var leftByX = pointsByX.Take(count / 2).ToList();
var leftResult = MyClosestRec(leftByX);
var rightByX = pointsByX.Skip(count / 2).ToList();
var rightResult = MyClosestRec(rightByX);
var result = rightResult.Length() < leftResult.Length() ? rightResult : leftResult;
var midX = leftByX.Last().X;
var bandWidth = result.Length();
var inBandByX = pointsByX.Where(p => Math.Abs(midX - p.X) <= bandWidth);
var inBandByY = inBandByX.OrderBy(p => p.Y).ToArray();
int iLast = inBandByY.Length - 1;
for (int i = 0; i < iLast; i++)
{
var pLower = inBandByY[i];
for (int j = i + 1; j <= iLast; j++)
{
var pUpper = inBandByY[j];
if ((pUpper.Y - pLower.Y) >= result.Length())
break;
Segment segment = new Segment(pLower, pUpper);
if (segment.Length() < result.Length())
result = segment;
}
}
return result;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (PointF p in points)
{
e.Graphics.DrawEllipse(new Pen(Color.Black), p.X - 1, p.Y - 1, 2, 2);
}
while (points.Count >= 2)
{
var result2 = MyClosestDivide(points);
e.Graphics.DrawLine(new Pen(Color.Green), result2.P1, result2.P2);
points.Remove(result2.P1);
points.Remove(result2.P2);
}
}
}
}
Sorry for my english and thanks for help,
Best regards
|
|
|
|
|
It looks like most of your code comes from RosettaCode.com: [^]; nothing wrong with that, although, it's generally a good thing to indicate the source of your code, since it might help people reading your post understand the context of your problem.
I am not clear what you are trying to do: are you attempting to take every point in the List of Points (except the last two which are identical ?), find the closest point to each of them (which would then give you a collection of pairs of points of approximately size = size-of-List / 2 ?
Please describe your goals in more detail.
"What Turing gave us for the first time (and without Turing you just couldn't do any of this) is he gave us a way of thinking about and taking seriously and thinking in a disciplined way about phenomena that have, as I like to say, trillions of moving parts.
Until the late 20th century, nobody knew how to take seriously a machine with a trillion moving parts. It's just mind-boggling." Daniel C. Dennett
|
|
|
|
|
I have a Visio ER diagram and want to read the database properties (Columns, Primary, Foreign key, data type) information from an Entity. Also want to find the parent and child tables associated. How can I programmatically achieve it using C#?
I am using Interop Visio library and can read the pages and shape from ER diagram but don't know which functions or methods in Visio interop will let me get properties information from a Shape.
Below is the code I am using and I am not getting any property using it. My ER diagram have just two entities a Parent and a Child table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Visio;
namespace Visio_POC
{
public partial class Load_Visio : Form
{
static string strProperties = "";
public Load_Visio()
{
InitializeComponent();
string strFileName = "\\Visio_POC\\POC_Visio.vsd";
Microsoft.Office.Interop.Visio.Application vsApp = new Microsoft.Office.Interop.Visio.Application();
Microsoft.Office.Interop.Visio.Document docVisio = vsApp.Documents.Add(strFileName);
Page pgVisio = docVisio.Pages[1];
printProperties(pgVisio.Shapes);
txtProperties.Text = strProperties;
}
public static void printProperties(Shapes shapes)
{
// Look at each shape in the collection.
foreach (Shape shape in shapes)
{
// Use this index to look at each row in the properties
// section.
short iRow = (short) VisRowIndices.visRowFirst;
// While there are stil rows to look at.
while (shape.get_CellsSRCExists(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsValue,
(short) 0) != 0)
{
// Get the label and value of the current property.
string label = shape.get_CellsSRC(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsLabel
).get_ResultStr(VisUnitCodes.visNoCast);
string value = shape.get_CellsSRC(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsValue
).get_ResultStr(VisUnitCodes.visNoCast);
// Print the results.
//Console.WriteLine(string.Format(
// "Shape={0} Label={1} Value={2}",
// shape.Name, label, value));
strProperties = strProperties + shape.Name + " - " + label + " - " + value;
// Move to the next row in the properties section.
iRow++;
}
// Now look at child shapes in the collection.
if (shape.Master == null && shape.Shapes.Count > 0)
printProperties(shape.Shapes);
}
}
}
}
|
|
|
|
|
Hi,
I am relatively new to c# and I am trying to utilize a background worker to run the progressBar however I am not getting beyond 1% in the following example. In the Form1_Load I have an iteration inside which I want to display the ProgressBar. Appreciate if someone can point out where I am going wrong with this logic.
Pat
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
float tot1=100;
float cnt1=0;
float rslt = 0;
int percents = 0;
public Form1()
{
InitializeComponent();
label1.Text = "";
label2.Text = "";
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
{
System.Threading.Thread.Sleep(500);
rslt = ((cnt1 / tot1) * 100);
percents = Convert.ToInt32(rslt);
bgw.ReportProgress(percents, cnt1);
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
private void Form1_Load(object sender, EventArgs e)
{
for (cnt1 = 0; cnt1 <= tot1; cnt1++) //some number (total)
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
if (!bgw.IsBusy)
{
bgw.RunWorkerAsync();
}
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
|
|
|
|
|
The problem appears to be in your DoWork function. You have no looping.
It runs the code in that function once and then the background thread exits.
Also, you put the loop in the FormLoad function, which is the wrong place for it. And you are adding delegates to the background worker inside that loop, which is wrong because you only need to add the delegates once.
Move your for loop to inside the DoWork function, and that should fix it.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I think you may find the example of using BackGroundWorker with ProgressBar, here, useful: [^].
bill
"What Turing gave us for the first time (and without Turing you just couldn't do any of this) is he gave us a way of thinking about and taking seriously and thinking in a disciplined way about phenomena that have, as I like to say, trillions of moving parts.
Until the late 20th century, nobody knew how to take seriously a machine with a trillion moving parts. It's just mind-boggling." Daniel C. Dennett
|
|
|
|
|
Here is most of your problem:
private void Form1_Load(object sender, EventArgs e)
{
for (cnt1 = 0; cnt1 <= tot1; cnt1++)
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
if (!bgw.IsBusy)
{
bgw.RunWorkerAsync();
}
}
} Each time round the loop, you construct a new worker, and kick it off to do the task. But...you only specify the one handler for all the workers, and you don't check in the handler method which worker you are processing for. And since you always write a value to the same label, you always get the one value from the last worker to execute.
Add that the worker doesn't do anything that takes much time, and only reports a single value, and it all looks a bit dodgy!
I've tidied it up a bit and made it so it should work:
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i <= 100; i++)
{
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i);
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
The only instant messaging I do involves my middle finger.
English doesn't borrow from other languages.
English follows other languages down dark alleys, knocks them over and goes through their pockets for loose grammar.
|
|
|
|
|
the problem is
i run my application-->selected one radio button -->then closed m application.
if i run my application next time ,that form should be opened by selecting the previous radio button. i need to store those values in app.config .how to store them dynamically in app.config
other than app.config plz give solution
|
|
|
|
|
You can update the App.Config during runtime[^]. Please remember that this may not work if your app.config is located in a read-only location, I'd therefore recommend you to use a second configuration file located in a writable location, e.g. the AppConfig folder to avoid crashes and malfunction of your program after it was not able to modify the app.config because it may read-only.
|
|
|
|
|
|
For using the settings.settings check out this MSDN Page[^]
Everything you need to know you should be able to find there
Probably you forgot to call the "Save" method after changing the value of the setting.
|
|
|
|
|
thanq. i forgot to call save().
|
|
|
|
|
for (int num = 0; num < treeList1.ViewInfo.RowsInfo.Rows.Count; num++)
{
}
All people for me query as a way that get the value of each line in TreeList, thanks.
|
|
|
|
|
Iterate the nodes; there's documentation here[^], and DevExpress has their own forum, specializing in their own products.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
What the use of this code:
foreach (TerminalGroup tg in vps) return tg;
Is there a benefit using this over something like:
if (vps.Length > 0) return vps[0]
I see this used more often, it's seems to be done deliberately.
|
|
|
|
|
I would suggest that the first version is lazy coding.
|
|
|
|
|
The first one also works when the collection is enumerable but has no indexer (though I don't really like that code even in that situation). Apart from that, AFAIK there's no point.
|
|
|
|
|
It's not some strange code trick that is a millisecond faster because it does less checks or so?
|
|
|
|
|
Depends on what the thing is.
For arrays, there is literally no difference. The assembly code generated by the JIT compiler is exactly the same, at least in my test case.
static int Test2(int[] array)
{
if (array.Length > 0)
return array[0];
throw new Exception();
}
static int Test1(int[] array)
{
foreach (int i in array)
return i;
throw new Exception();
}
push rbx
sub rsp,20h
mov rax,qword ptr [rcx+8]
test eax,eax
jle 0000000000000020
test rax,rax
jbe 0000000000000040
mov eax,dword ptr [rcx+10h]
add rsp,20h
pop rbx
ret
For other things, of course you can construct a type such that indexing is slow (always, also at index 0) and enumeration is fast, but usually starting to enumerate means setting up a little state machine (takes some non-zero but usually tiny amount of time) and indexing at index 0 is usually trivial.
TL;DR I would guesstimate that the second way is faster more often than it is slower.
|
|
|
|
|
Hello,
In my program I need to be checked if the database was deleted, the program creates it again. So, I made a database and connected it to my program with 'LINQ-To-SQL-Classes', when I delete the database manually ("Database1.mdf" and "Database1_log.ldf"), it cannot create the database and show me this error:
" Database 'C:\Users\Saleh\documents\visual studio 2010\Projects\St\St\bin\Debug\Database1.mdf' already exists. Choose a different database name. "
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
string strDBPath = Application.StartupPath + ("\\Database1.mdf");
DataClasses1DataContext objDB = new DataClasses1DataContext(strDBPath);
if (!objDB.DatabaseExists())
{
objDB.CreateDatabase();
MessageBox.Show("Database created!");
}
}
How can I handle it?
Thanks in advance!
|
|
|
|
|
am placing interval value in app.config as
<add key="TCPIP" value="192.168.2.130"/>
<add key="tcpport" value="6000"/>
<add key="tcpadderss" value="FF"/>
<add key="comaddress" value="FF"/>
<add key="interval" value="200"/>
then now i want to assign that value to combobox in c#
textBox8.Text = System.Configuration.ConfigurationManager.AppSettings["TCPIP"];
textBox7.Text = System.Configuration.ConfigurationManager.AppSettings["tcpport"];
textBox9.Text = System.Configuration.ConfigurationManager.AppSettings["tcpadderss"];
Edit_CmdComAddr.Text = System.Configuration.ConfigurationManager.AppSettings["comaddress"];
comboBox1.SelectedItem= System.Configuration.ConfigurationManager.AppSettings["interval"];
in case of textboxes it's working fine. but how to assign interval value to combox.when i run the project form shoul load with that interval value
|
|
|
|
|
If for your combobox value and text both are same then you may use comboBox1.SelectedValue .
Regards,
CodeBlack
|
|
|
|
|
thanq i got it. but now the problem is
i run my application-->selected one radio button -->then closed m application.
if i run my application next time ,that form should be opened by selecting the previous radio button. i need to store those values in app.config .how to store them dynamically in app.config
-- modified 8-Nov-13 5:10am.
|
|
|
|
|
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["test"].Value = "blah";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
It was worked for me.
Don't forget to mark it as an answer.
Regards,
CodeBlack
|
|
|
|
|