|
First, this is an English speaking site. You would have easily figured that out just by looking around.
From Bing Translate:
Quote: Hello together,
I'm trying to implement your own IFormatProvider.
Here are two examples:
-String.Format() - works correctly as expected
-int. ToString() - doesn't work as expected!
Below is the code:
-FormatProvider for the format method:
Quote: The call:
Quote: The output (makes no sense, but works as expected):
Quote: Now to the problem:
-Format provider for ToString():
Quote: The output:
Exception ' format specifier which invalid. "
I don't understand what I am doing wrong.
Has a tip, an example or a corrected version me someone?
Thanks for the help. Regards, Manfred
|
|
|
|
|
I'm not sure what are you trying to achieve with this piece of code:
int i = 123;
IFormatProvider fpToString = new FormatProviderToString();
Console.WriteLine(i.ToString("A", fpToString) + " " + i.ToString("B", fpToString) + " " + i.ToString(fpToString));
What kind of output you do expect: AA BB 3 ?
I'd suggest to read this: Formatting Types in the .NET Framework[^]
|
|
|
|
|
I have a bindinglist then i store the indexes to dictianary<int, int=""> for fast access to the bindinglist.
then i have something like this
var dIndex = new Dictionary<int, int>()
now i face a problem when removing the item in the bindiglist, because the indexes stored in the dictionary doesnt correspond anymore in the bindinglist.
so my solution is to re-arrange the indexes.
Then i got this.
int id = thisObject.ID;
if(dIndex.ContainsKey(id))
{
data.RemoveAt(dIndex[id]);
_dIndex.remove(id);
foreach(var key in dIndex.keys)
{
if(dIndex[key] > id)
{
dIndex[Key]--;
}
}
}
If I am correct, rearranging the index (the value of the dictionary) using the foreach loop above could result to an O(n).
could anyone here can give me much better solution than this.
I will appreciate for any advice.
Thank you.
|
|
|
|
|
I suggest you use a direct reference to the object(s) in the Binding List for the Value field of the generic Dictionary, rather than an index to their position in a List; since what you will actually store is a pointer, this will not consume much more memory than storing an Int16, or Int32.
In my mind, that also raises the question of why use a List when you are using a Dictionary ... however, I can't see your code, and don't know in what other ways you may be using the List.
private Dictionary<int, BindingListObject> IDToBindingListObject = new Dictionary<int, BindingListObject>();
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Yes you are right, i use the dictionary as pointer to the object, I used the key as the object id and the value as the pointer to the object. I will also use the bindinglist as a datasource. For my first implementation I am aware that it has a memory penalty, and need much more work.
I got just worried about this line of code, how would it impact the performance.
foreach(var key in dIndex.keys)
{
if(dIndex[key] > id)
{
dIndex[Key]--;
}
}
I think the remove(object) method of bindinglist has already been optimized by MS.
Thank you for your suggestion, Ill try it. I think there is no way to achieve O(1) for deleting object on the bindinglist.
|
|
|
|
|
I have created X number of ComboBoxes (PartNo) dynamically, that depending on the number selected in it, it will pull/populate some textboxes with Part Information.
All boxes have been given a Key value of cboBox1, cboBox2, etc.
How can I make an event for these comboboxes?
private void cboBox1_SelectedIndexChanged(object sender, EventArgs e)
Not sure if it matters, but the comboboxes are all part of a panel (pn), so maybe it would be?
private void pn.cboBox1_SelectedIndexChanged(object sender, EventArgs e)
I hate not knowing what I don't know.
|
|
|
|
|
Get a reference to the combo box and use, e.g.
SomeComboBox.SelectedIndexChanged += SomComboBox_SelectedIndexChanged;
Where SomeComboBox is the name of your combo box reference, e.g. cboBox1.
What do you get when you cross a joke with a rhetorical question?
The metaphorical solid rear-end expulsions have impacted the metaphorical motorized bladed rotating air movement mechanism.
Do questions with multiple question marks annoy you???
|
|
|
|
|
I suggest that in the code that creates the ComboBoxes at run-time, you wire-up the same 'SelectedIndexChanged EventHandler to each new ComboBox:
cmbx = new ComboBox();
cmbx.SelectedIndexChanged += CmBoxIndexChanged;
private void CmBoxIndexChanged(object sender, EventArgs e)
{
if (sender == null) throw new ArgumentNullException("Error in ComboBox SelectedIndexChanged");
ComboBox caller = sender as ComboBox;
switch (caller.Name)
{
case "ComboBox0":
break;
case "ComboBox1":
break;
}
}
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Sorry to not respond earlier, but your solution works perfectly.
Thanks all for your help!
|
|
|
|
|
Hi all,
If you know all the ComboBoxes are inside the panel, why not just iterate of the Panel's ComboBox controls?
foreach (ComboBox cBox in panel1.Controls)
{
cBox.SelectedIndexChanged += cBox_SelectedIndexChanged;
}
Then when any of the ComboBox's SelectedIndexChanged events fire, you capture which one it is and do what needs to be done. eg.
void cBox_SelectedIndexChanged(object sender, EventArgs e)
{
var currentComboBox = sender as ComboBox;
if (currentComboBox == null)
return;
MessageBox.Show(currentComboBox.SelectedItem.ToString());
}
Neill
|
|
|
|
|
You could also consider using anonymous functions and lambda expressions if the function that is dynamically creating the combo box is also aware of what the drop down needs to do when updated.
public void AddComboBox(ComboBox cBox, Action<int> callback)
{
cBox.SelectedIndexChanged += (s,e) => { callback(cBox.SelectedIndex); };
}
|
|
|
|
|
The downside of this approach is that you've created a non-disposable event handler with that syntax.
|
|
|
|
|
Yes, you are correct that it would leak resources. If this were a long running application than that would be a problem otherwise the flexibility gained can potentially outweight a few kb of in memory comboboxes not reclaimed by the garbage collector. Another approach would to have an IDisposable class derive from combobox and reclaim the handler in Dispose() when the dynamically created boxes are deleted from their container.
|
|
|
|
|
public void GetBackup(string strDBName)
{
if (string.IsNullOrEmpty(strDBName))
{
MessageBox.Show("Server Name & Database can not be Blank");
return;
}
else
{
string destinationPath = ConfigurationManager.AppSettings.Get("BackupDestinationPath");
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
ServerConnection connection = new ServerConnection(ConfigurationManager.ConnectionStrings["CostAllocationEntities2"].ConnectionString);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[strDBName];
The above line Database db = sqlServer.Databases[strDBName]; is causing the below mentioned error.
Error : "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not> found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"}
Message : Failed to connect to server D>ata
Source=PC210090\\SQLEXPRESS;Initial Catalog=testdb2;Persist Secur>ity
Info=True;User ID=sa;password=password-1"}
|
|
|
|
|
The error message is pretty explicit, and even tells you what to do.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
So look at your connection string, and make sure that it is correct, and that the computer you are running your application on can "see" the "PC210090" PC on it's local network segment. Then check the user name and password combination is also correct.
And don't use the SA user login - it has complete access to the databases, you should be using a user with specific permissions at all times.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Yeah, the error is pretty self explanatory,a nd OriginalGriff is right, don't use sa account.
That being said; Did posting the code mess up your connection string or is that whats wrong? Also why are there 2 \'s between hostname and instance name?
Message: Failed to connect to server D>ata
Source=PC210090\\SQLEXPRESS;Initial Catalog=testdb2;Persist Secur>ity
Info=True;User ID=sa;password=password-1
Neill
|
|
|
|
|
My Connection string :
<add name="CostAllocationEntities2" connectionString="Data Source=PC210090\SQLEXPRESS;Initial Catalog=testdb2;Persist Security Info=True;User ID=sa;password=password-1" providerName="System.Data.SqlClient"/>
|
|
|
|
|
Well the connection string format looks fine.
There could still be quite a few things causing the problem.
1. Are your sure the PC210090 name is correct?
2. Is SQLEXPRESS correct or are you using a named instance?
3. Is the DB name correct?
4. Is the username correct?
5. is the password correct?
If you have SQL Management Studio installed on your machine, can you connect to the database from there using the username and password?
In Visual Studio, try creating a connection from the Server Explorer window.
Is PC210090 where the db server is located the same machine you are using? It could be a firewall issue.
There are really quite a few reasons as to why its could not be working.
Neill
|
|
|
|
|
Another thing that I am confused by (which happens far too easily.) is if you are using a specific framework?
Why create ServerConnection with the specified ConnectionString which specifies the initial database, and then attempt sqlServer.Databases[strDBName] which is the database name passed into the method?
Neill
|
|
|
|
|
I can download small size of application but could not download big size of application. It shows out of memory.
Below is my code:
string Files = ListBox1.SelectedValue;
byte[] fileBytes = System.IO.File.ReadAllBytes(Files);
WebClient User = new WebClient();
byte[] FileBuffer = User.DownloadData(Files);
if (FileBuffer != null)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-length", FileBuffer.Length.ToString());
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(Files));
context.Response.BinaryWrite(FileBuffer);
context.ApplicationInstance.CompleteRequest();
Could pls anyone help...
|
|
|
|
|
Member 12016106 wrote: byte[] fileBytes = System.IO.File.ReadAllBytes(Files); Do not assume that there is enough memory to hold the entire file.
|
|
|
|
|
So how should declare it to download large size file??
|
|
|
|
|
Simply put, computers don't have unlimited memory. Determine a reasonable buffer size and read the file in chunks of that size, processing each one in turn.
If your data has any kind of structure (either fixed size blocks, or flexible e.g. XML) you should make use of that to work out how to read and process it in smaller pieces.
I can't tell from your sample code what you're trying to do, but it appears you're accessing both local and remote files, either of which could be much larger than your available memory. You need to think through what processing you need to do, and how to achieve it within the limits.
Days spent at sea are not deducted from one's alloted span - Phoenician proverb
|
|
|
|
|
You have several options:
TransmitFile is the preferred method:
string physicalPath = ListBox1.SelectedValue;
if (!string.IsNullOrWhiteSpace(physicalPath))
{
FileInfo fileToSend = new FileInfo(fileToSend);
if (fileToSend.Exists)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-length", fileToSend.Length.ToString());
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlPathEncode(fileToSend.Name));
context.Response.TransmitFile(fileToSend.FullName);
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
}
}
WriteFile will work in the same way, but can have problems with large files[^].
Reading the file in small blocks requires more code, and won't perform as well as TransmitFile :
int bytesRead;
byte[] buffer = new byte[10000];
using (Stream fileStream = fileToSend.OpenRead())
{
while (context.Response.IsClientConnected && (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
context.Response.Flush();
}
}
context.ApplicationInstance.CompleteRequest();
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello,
I am learning to develop in C # on my own which is not an easy thing.
I try to dynamically generate a name for answer my objects.
example:
ComboBox myCombo1 = new ComboBox ();
AND
myCombo1.Text = "Blabla";
What I would like is generated dynamically (myCombo1, myCombo2, myCombo3)
Is this possible or is there a class my question?
Thank you in advance for your help.
Alexandre
|
|
|
|