|
ooh, I hope one of the categories is
SQL Injection - how to do it';drop table book_list;' Let me know the URL when it's live
Seriously, parameterise that.
|
|
|
|
|
Hello All,
I am still pretty new to C# and have run into a little issue.
I have program which passes data into Excel and can be used on the same workbook many times. Therefore, I need to check to see if cell 7,1 (for instance) already contains data from a previous pass and if so, move to cell 11,1, do the same test and if that has data, move to cell 15,1 etc. etc. I think I possibly require some sort of Switch statement where we keep falling through until the specified cell is empty and therefore ready to receive data, i.e. look at 7,1 > 11,1 > 15,1 > 19,1 right down to row number 55 (the cell rows increase by multiples of 4) but I am struggling with it.
Can anyone provide the best practice for doing this?
Thanks,
Steve
modified 22-Mar-21 12:44pm.
|
|
|
|
|
The whole thing sounds pretty fragile; and without some "what for", a pointless mental exercise.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
OK Gerry, here is the full scenario.
My program functions inside of AutoCAD and is intended to export some product data to a "Packing List"
which is a spreadsheet in Excel.
This is the workflow:
1. The draughtsman is prompted to make a selection from a number of products (AutoCAD entities) on the drawing which will comprise of the items to be added to the Packing List.
2. He then allocates the selection to a Bundle number, which he is prompted for and defines himself.
3. The program then looks for an excel book with the same name as the drawing file and if it does not exist, creates a new one from a defined template.
4. It then iterates through the selection set and extracts all of the part numbers and builds a string of the numbers to be written out i.e. 1, 2, 3, 4, 5 etc.
5. If we are in a new workbook, the string is written into the first cell at row 7.
6. The workbook is then saved and closed.
7. When this process is finished, the draughtsman can then start over again and make another selection which he then allocates to a different Bundle number.
8. At this point, the program finds the existing workbook and opens it, but now needs to start at the first cell on row 11 as cell 7, 1 already holds data.
This workflow can carry-on upto 13 times, when the last row will be reached.
Hope this is clearer.
Steve
ps I can't see how to include a snapshot of the packing list spread sheet.
|
|
|
|
|
It is a simple loop:
bool found = false;
for (int row = 7; row < 56; row += 4)
{
if (cell[row, 1] is empty
{
found = true;
break:
}
}
if (!found)
{
}
|
|
|
|
|
Hi Richard,
Thanks for your suggestion. I will try this later today and let you know how I get on.
Steve
|
|
|
|
|
Hi Richard,
Thanks for pointing me in the right direction.
I changed your suggestion as below...it works a treat!
for (int row = 7; row < 56; row += 4)
{
if (workSheet.Cells[row, 1] == null || workSheet.Cells[row, 1].Value2 == null || workSheet.Cells[row, 1].Value2.ToString() == "")
{
workSheet.Cells[row, 1] = (string)fillinData.GetValue(0);
workSheet.Cells[row + 1, 18] = (string)fillinData.GetValue(1);
workSheet.Cells[row - 1, 10] = (string)fillinData.GetValue(8);
break;
}
}
Thanks again,
Steve
|
|
|
|
|
|
Greetings!
Does anyone know how an XML (an example is given below) file created in the Mike Hankey`s GRADIATOR
program would be written in C# itself?
Specifically I mean the full definition of brush.
GraphicsPath g = new GraphicsPath();
PathGradientBrush brush = new PathGradientBrush(g);
.
.
.
Thanks in advance, Aleksandar
p.s. https://www.codeproject.com/Articles/20018/Gradients-made-easy
example:
<ShapeObjects>
<ShapeObject>
<Id>28316747</Id>
<Rectangle>200,201,384,384</Rectangle>
<FontFamily>Palatino Linotype</FontFamily>
<FontSize>10</FontSize>
<Text>
</Text>
<Type>Elliptical</Type>
<HasBorder>True</HasBorder>
<BrushName>
</BrushName>
<FillType>pathGradient</FillType>
<Color>Color [A=255, R=255, G=255, B=255]</Color>
<Color1>Color [Black]</Color1>
<Color2>Color [A=255, R=180, G=180, B=180]</Color2>
<LinearAngle>90</LinearAngle>
<CenterPoint>{X=0.5104167, Y=0.5104167}</CenterPoint>
<UseSigmaShape>True</UseSigmaShape>
<UseBlendShape>False</UseBlendShape>
<SurroundColors>Color [A=255,R=0,G=27,B=82]</SurroundColors>
<Focus>0.507451</Focus>
<Scale>0.6080391</Scale>
<Positions>0,1</Positions>
<Factors>0.2,0.8</Factors>
<UseBlend>False</UseBlend>
<UseColorBlend>False</UseColorBlend>
<UseGammaCorrection>False</UseGammaCorrection>
<FocusScale>{X=0.8039216, Y=0.8015845}</FocusScale>
</ShapeObject>
</ShapeObjects>
|
|
|
|
|
If you have a question about the code in an article, post it in the forum at the bottom of that article. That way, the author will be notified and will have a chance to respond to your question.
Mike is still quite active here.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks with an apology, Aleksandar
|
|
|
|
|
UWP and WPF employ gradient brushes (C#, XAML) that reflect what you've shown in XML.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Thanks Garry!
Although I don't quite understand (because I am an absolute c# beginner) the complete answer.
Does this apply if the WPF App (.NET Framework) is used?
What if you use the Windows Form App (.NET Framework)?
I tried to add a couple of lines but it doesn't go further ..
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(0,0,96,96);
PathGradientBrush ringKnob = new PathGradientBrush(gp);
ringKnob.CenterPoint = new PointF(49.0f, 49.0f);
ringKnob.CenterColor = Color.FromArgb(255, 180, 180, 180);
ringKnob.SurroundColors = new Color[]{
Color.FromArgb(255, 0, 27, 82)
};
Blend blnd = new Blend();
blnd.Positions = new float[] { 0.0f, 1.0f };
blnd.Factors = new float[] { 0.2f, 0.8f };
Can XML be interpreted in this way?
|
|
|
|
|
I found another solution, the topic locked
|
|
|
|
|
I have a simple Windows Form with textbox. When form is loading, I start another class with counter. How to write to Form1.textBox1 from another class?
namespace Test_CSharp
{
public partial class Form1 : Form
{
public static Form1 form1;
public Form1()
{
InitializeComponent();
form1 = this;
}
private void Form1_Load(object sender, EventArgs e)
{
Run_Nonameclass();
}
private void Run_Nonameclass()
{
Nonameclass newNonameclass = new Nonameclass();
}
}
}
namespace Test_CSharp
{
class Nonameclass
{
private System.Timers.Timer mycounter;
public int cnt;
Form1 frm = new Form1();
public Nonameclass()
{
cnt = 0;
mycounter = new System.Timers.Timer();
mycounter.Interval = 1000;
mycounter.Start();
mycounter.Elapsed += mycounter_Tick;
}
private void mycounter_Tick(object source, System.Timers.ElapsedEventArgs e)
{
try
{
cnt = cnt + 1;
frm.textBox1.Text = cnt.ToString();
}
catch (Exception ex)
{
}
}
}
}
|
|
|
|
|
You can't.
The Tick event happens asynchronously, but occurs on the same thread as the original code - so if your code starts a timer and then does a long running operation while loading you still won't see anything. The only way to get round that is to move the long running operation to a second thread (see the BackgroundWorker class[^] and report progress to the main thread to update the display.
And your code won't work, because your Nonameclass creates a new instance of the Form1 class which is never displayed. To display anything you would need to access the actual instance that created the Nonameclass instance and that means passing the Form1 instance to the constructor. Which is a bad idea, because it breaks OOPs and locks the two class designs together, as does exposing the TextBox publicly in your Form1 class!
You need to think about exactly what you are trying to achieve here, because the route you are trying to go is a bad idea. What you really want to do is probably possible, and even quite easy - but this way is not a good route to that (or anything else!)
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi, Folks.
I have a problem and expect you can help me. I use C# in Visual Studio 2019. I have a combobox which I populated with a table data. I used a Datasource to do this. When the user selects a value I need a variable to receive the string value of the combobox.
My snippet is as folows:
private void Cb_Campo_SelectionChangeCommitted(object sender, EventArgs e)
{
if (_Modo != 0)
{
Cb_Campo.DisplayMember = CampoTexto;
Cb_Campo.ValueMember = CampoChave;
ValorChave = int.Parse(Cb_Campo.SelectedValue.ToString());
ValorTexto = Cb_Campo.SelectedItem.ToString();
}
}
Before selection, the combobox has "Select" as a text. Tha variable ValorChave is receiving the correct value, but the variable ValorTexto, with the code above, receives "System.Data.DataRowView".
If I change that line for
ValorTexto = Cb_Campo.Text
The result is "Select", which is the initial text.
Obviously, what I need is the corresponding value to the SelectedValue.
Can anyone help me solve this?
Thanks a lot.
|
|
|
|
|
The SelectedItem is a DataRow - as you'd expect because the ComboBox is bound to a DataSource.
And because DataRow is a "generic" class (in that it handle multiple types of data simultaneously) it doesn't handle ToString itself as it has no idea which bit(s) of data you might want it to convert to a string.
Try the Text property instead.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi, OriginalGriff.
As you can see in the main text, I've tried this, but is appears the combobox has't yet considered the selection the user did. Do you have any other sugestion?
Thanks.
|
|
|
|
|
Are you using Autocomplete ? Did you try:
tryValorTexto = Cb_Campo.SelectedValue.ToString(); ?
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
|
|
|
|
|
I use FFMediaToolkit package to do some video task like extract frame and remake video from frame image. My code sometime raise exception like below. I try to add try-catch block to handle it but no luck. Pls show me how to handle exception from ffmpeg lib.
Exception info:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at FFMediaToolkit.Decoding.Internal.InputContainer.ReadPacket() in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\Internal\InputContainer.cs:line 174
at FFMediaToolkit.Decoding.Internal.InputContainer.GetPacketFromStream(Int32 streamIndex) in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\Internal\InputContainer.cs:line 90
at FFMediaToolkit.Decoding.Internal.Decoder.DecodePacket() in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\Internal\Decoder.cs:line 146
at FFMediaToolkit.Decoding.Internal.Decoder.ReadNextFrame() in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\Internal\Decoder.cs:line 136
at FFMediaToolkit.Decoding.VideoStream.GetNextFrame() in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\VideoStream.cs:line 51
at FFMediaToolkit.Decoding.VideoStream.TryGetNextFrame(ImageData& bitmap) in C:\projects\ffmediatoolkit\FFMediaToolkit\Decoding\VideoStream.cs:line 68
|
|
|
|
|
We can't help you at all based on that: your code is calling an external DLL and passing bad data, eitehr in the form of a bad media, or a bad address for data.
And since we can't see your code at all, we have no idea what functions you are calling, how you are calling them, or what data you might be passing.
Sorry, but you will have to sort this out yourself!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
 here is my code that using ffmpeg lib, it's extract frame in video file and do something else. The exception may raise at any time and my question is not find out why exception occur. I only want to know why I already add try-catch block to my code but when the exception raised, it make my app crash instead of jump to the cach block?
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
private void timerCallback(object state)
{
MediaFile file = null;
long startTick = DateTime.Now.Ticks;
try
{
if (PlayListInfo == null || PlayListInfo.Count == 0) return;
int idx = 0;
bool newVideo = true;
TimeSpan endTime = new TimeSpan();
double time_4_frame_ms = 0;
while (idx < PlayListInfo.Count && !request_stop)
{
var startProcess = DateTime.Now;
var curVideo = PlayListInfo[idx];
bool firstFrame = false;
if (newVideo)
{
if (file != null) file.Dispose();
startTick = DateTime.Now.Ticks;
file = MediaFile.Open(curVideo.fileName);
newVideo = false;
endTime = curVideo.stopTime < 0 ? file.Info.Duration : TimeSpan.FromSeconds(curVideo.stopTime);
if (!file.HasVideo)
{
Console.WriteLine($"Cannot load video file: {curVideo.fileName}");
}
else
{
Console.WriteLine($"Process video: {curVideo.fileName}, frame rate: {file.Video.Info.AvgFrameRate}");
time_4_frame_ms = file.Video.Info.NumberOfFrames == null ? 0 : file.Video.Info.Duration.TotalMilliseconds / file.Video.Info.NumberOfFrames.Value;
firstFrame = true;
}
}
TimeSpan sp = new TimeSpan(DateTime.Now.Ticks - startTick);
sp.Add(TimeSpan.FromSeconds(curVideo.startTime <= file.Info.StartTime.TotalSeconds ? file.Info.StartTime.TotalSeconds : curVideo.startTime));
ImageData img;
if (sp > endTime)
{
idx++;
newVideo = true;
continue;
}
if (file != null && file.HasVideo)
{
var t1 = DateTime.Now;
bool ck = false;
if (firstFrame)
{
ck = file.Video.TryGetFrame(sp, out img);
firstFrame = false;
}
else
{
do
{
ck = file.Video.TryGetNextFrame(out img);
}
while (ck && file.Video.Position < sp);
}
if (!ck)
{
Console.WriteLine($"Cannot read frame at {sp} of {curVideo.fileName}");
idx++;
newVideo = true;
continue;
}
else
using (var bitmap = ToBitmap(img))
{
var frametime = DateTime.Now - t1;
if (checkBlankFrame(bitmap))
{
Console.WriteLine($"Found black frame at {sp} of {curVideo.fileName}");
}
else ProcessFrame(bitmap);
}
}
var processTime = DateTime.Now - startProcess;
int sleeptime = (int)(time_4_frame_ms - processTime.TotalMilliseconds);
if (sleeptime > 0)
System.Threading.Thread.Sleep(sleeptime);
}
}
catch (AccessViolationException ex)
{
Console.WriteLine(ex.ToString());
}
catch
{
}
finally
{
if (file != null)
{
try
{
file.Dispose();
}
catch
{
}
file = null;
}
}
}
here is the source code for making video from bitmap:
private unsafe void PushFrame(Bitmap bitmap)
{
try
{
lock (this)
{
var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
try
{
int len = data.Stride * data.Height;
byte[] bitmapData = new byte[len];
Marshal.Copy(data.Scan0, bitmapData, 0, len);
if (frameList.Count == 0) startTime = DateTime.Now.Ticks;
frameList.Add(bitmapData);
}
finally
{
bitmap.UnlockBits(data);
}
TimeSpan sp = new TimeSpan(DateTime.Now.Ticks - startTime);
if (sp.TotalSeconds >= Properties.Settings.Default.LiveVideoDuration)
{
if (frameList.Count == 0) return;
videoCount++;
videoIndex = videoCount % 10;
var settings = new VideoEncoderSettings(width: bitmap.Width, height: bitmap.Height,
framerate: (int)(frameList.Count / sp.TotalSeconds), codec: VideoCodec.H264);
settings.EncoderPreset = EncoderPreset.Fast;
settings.CRF = 17;
string path = $"{VideoFolder}\\{videoIndex}.{videoExt}";
using (var mediaFile = MediaBuilder.CreateContainer(path).WithVideo(settings).Create())
{
Console.WriteLine($"create video: {MappingFile}.{videoIndex}.{videoExt} -- duration: {sp.TotalSeconds}, total frame: {frameList.Count}");
foreach (var item in frameList)
{
Span<byte> imgData = new Span<byte>(item, 0, item.Length);
mediaFile.Video.AddFrame(new ImageData(imgData, ImagePixelFormat.Bgr24, bitmap.Size));
}
AddFileToPlayList(videoCount, $"{videoIndex}.{videoExt}", (decimal)sp.TotalSeconds);
}
frameList.Clear();
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
|
|
|
|
|
I am not going to sit here and wade through an entire, badly indented, unformatted, uncommented, large application that I can't even begin to test to try and work out where an error might be happening, and from that what might possibly be causing it.
Would you?
Use the debugger. Narrow down where it fails, and when it fails. Look at the variables you are passing to methods when it fails. Compare them against what you expected.
We can't do any of that for you!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Oh may be my english is not good enough so you still confuse about the code sample. You don't need to understanding what I doing in the code statement. Just look at that then you will see the try-catch block cover all code that I use ffmpeg lib to do. My question is: when exception from ffmpeg raised, why it let my application scrash instead of jump to catch statement.
|
|
|
|
|