STACKOVERFLOW
gold badges
silver badges
bronze badges
What's does the dollar sign ($"string") do?
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
- interpolatedExpression - The expression that produces a result to be formatted
- alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
- formatString - A format string that is supported by the type of the expression result.
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
How do I split a string on an empty line using .Split()?
You can get it accomplished by using
string[] people = record.Split(new string[] { "\r\n\r\n" },
StringSplitOptions.RemoveEmptyEntries);
or
string[] people = record.Split(new string[] { Environment.NewLine + Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
What it does is it removes empty entries with StringSplitOptions.RemoveEmptyEntries
and then splits where two linebreaks are right after each other.
RegEx to allow all characters, length should be 1-50 characters
For the exact length of the string, you could use
^.{50}$
Whereas to check the length range you can use
^.{5,50}$
It might be more sensible for real users if I also included a lower limit on the number of letters.
If you wanted to just check the minimum length you can use
^.{50,}$
Now a string of at least fifty letters, but extending to any length,
^.{0,50}$
This will match a whole string containing between 0 and 50 (inclusive) of any character. Though regular expressions are probably the wrong tool for this job. Regex is overkill; just check the length of the string. You should have used String.Length
for this, like:
if(UrString.Length > 0 && UrString.Length <= 50)
How to get title tag using HTML Agility Pack
This might do the trick for you
doc.DocumentNode.SelectSingleNode("//head/title");
or
doc.DocumentNode.SelectSingleNode("//title");
or
doc.DocumentNode.Descendants("title").FirstOrDefault()
Using JsonUtility.FromJson to deserialize JSON in Unity
Your class should look like this
[System.Serializable]
public class PlayerInfo
{
public List<ActData> data;
public int status;
}
[System.Serializable]
public class ActData
{
public int id;
public string layoutLabel;
public int hasCustomProb;
}
Wrap every method in try-catch or specific part of code
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
You can have a look on How often should I use try and catch
The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.
Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.
Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.
Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.
Best way to create dynamic html in c#
If you look at the Maintainence prespective you can actually make a HTML file with placeholders like this
<table class="paddingIndendation" style="width: 100%;" border="1">
<tr>
<td>Location ~LocationNumber~</td>
<td>:</td>
<td>~AddressLine1~</td>
</tr>
<tr>
<td colspan="2" style="text-align:right;"></td>
<td>~AddressLine2~</td>
</tr>
<tr>
<td colspan="2" style="text-align:right;"></td>
<td>~PostalCode~ ~City~</td>
</tr>
Load the string in a string variable like
string htmlstring = File.ReadAllText("yourhtml.txt");
And then probably you can create a small function where you can replace all these placeholders with whatever properties or database call like this
htmlstring = htmlstring.Replace("~LocationNumber~",location.LocationNumber);
htmlstring = htmlstring.Replace("~AddressLine1~",location.AddressLine1);
htmlstring = htmlstring.Replace("~AddressLine2~",location.AddressLine2);
htmlstring = htmlstring.Replace("~PostalCode~",location.PostalCode);
htmlstring = htmlstring.Replace("~City~",location.City);
How can I make SQL Server 2012 truncate insertions if they are too big?
Normally, SQL Server will present an error on any attempt to insert more data into a field than it can hold
String or binary data would be truncated. The statement has been terminated.
SQL Server will not permit a silent truncation of data just because the column is too small to accept the data. But there are other ways that SQL Server can truncate data that is about to be inserted into a table that will not generate any form of error or warning.
By default, ANSI_WARNINGS are turned on, and certain activities such as creating indexes on computed columns or indexed views require that they be turned on. But if they are turned off, SQL Server will truncate the data as needed to make it fit into the column. The ANSI_WARNINGS setting for a session can be controlled by
SET ANSI_WARNINGS { ON|OFF }
Unlike with an insert into a table, SQL Server will quietly cut off data that is being assigned to a variable, regardless of the status of ANSI_WARNINGS. For instance:
declare @smallString varchar(5)
declare @testint int
set @smallString = 'This is a long string'
set @testint = 123.456
print @smallString
print @testint
Results is:
This
123
This can occasionally show itself in subtle ways since passing a value into a stored procedure or function assigns it to the parameter variables and will quietly do a conversion. One method that can help guard against this situation is to give any parameter that will be directly inserted into a table a larger datatype than the target column so that SQL Server will raise the error, or perhaps to then check the length of the parameter and have custom code to handle it when it is too long.
For instance, if a stored procedure will use a parameter to insert data into a table with a column that is varchar(10), make the parameter varchar(15). Then if the data that is passed in is too long for the column, it will rollback and raise a truncation error instead of silently truncating and inserting. Of course, that runs the risk of being misleading to anyone who looks at the stored procedures header information without understanding what was done.
How do you include many additional files with ClickOnce deployment?
Add the files to your project. Mark the Build Action as Content
and the Copy to local directory
to Always
. Then it will include the files with your deployment.
You can also check the Application Files dialog to see if they are there. And if the files have a file extension of XML or something that indicates data, you want to change the option from Include(Data)
to Include
or Include(Required)
. If you include a file as data, it is put in the DataDirectory after deployment.
- Select a data file in Solution Explorer.
- In the Properties window, change the Build Action property to the Content value
2. To mark files as data files
- With a project selected in Solution Explorer, on the Project menu, click Properties.
- Click the Publish tab.
- Click the Application Files button to open the Application Files dialog box.
- In the Application Files dialog box, select the file that you wish to mark as data.
- In the Publish Status field, select Data File from the drop-down list.
3. To mark files as prerequisites
- With a project selected in Solution Explorer, on the Project menu, click Properties.
- Click the Publish tab.
- Click the Application Files button to open the Application Files dialog box.
- In the Application Files dialog box, select the application assembly (.dll file) that you wish to mark as a prerequisite. Note that your application must have a reference to the application assembly in order for it to appear in the list.
- In the Publish Status field, select Prerequisite from the drop-down list.
Source: MSDN - How to: Specify Which Files Are Published by ClickOnce
Unable to cast object of type 'System.DateTime' to type 'System.String'. c#
You can try like this
list.Add(myReader["Date"].ToString());
If you want you can also apply formatting to your date in the ToString(dd-MM-yyyy) using Custom Date and Time Format Strings
DataView.RowFilter in DataTable does not return filtered records
I believe this might solve your problem.
DataTable dt = new DataTable();
dt = GetAccCode(c);
DataView dv = new DataView(dt);
dv.RowFilter = "AccountDescription LIKE '%" + e.Text + "%'" ;
dv.RowFilter = "Isnull(AccountDescription,'') <> ''";
dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
if (dv.Count > 0)
{
dt = dv.ToTable();
}
Just for testing purposes you can also hard code the values and see if it changes the result. for example:
dv.RowFilter = "AccountDescription LIKE '%mo%'" ;
and omit or comment the line
//dv.RowFilter = "Isnull(AccountDescription,'') <> ''";
to see what results you get.
Drawing text on image
I am sure you might be looking for this.
rectf = new RectangleF(655, 460, 535, 90); //rectf for My Text
using(Graphics g = Graphics.FromImage(myBitmap))
{
//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString("My\nText", new System.Drawing.Font("Tahoma", 32, FontStyle.Bold), Brushes.Black, rectf, sf);
}
//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90);
Line is used to show where your text will be written. So before you actually make your make your text You can see where this rectanlge will be created on the image. If you want the center of the image you can find the height and width and divide that by 2 to find the center of the image and than can plot the rectangle parameters accordingly.
One or more unit test projects for solution
If the question is only Can a single unit test project that can handle all three? The answer is Yes but than to proceed next step I would say it depends. Personally, I tend to put all of the tests in a single project, with separate folders within the project for each assembly (plus further sub-folders as necessary.) This makes it easy to run the entire set within VisualStudio. If you have thousands of tests, a single project might prove too difficult to maintain. We usually split them out because we don't want to deploy them with our product. Whether you split them out per library or per solution there are merits to both.
Ultimately, you want tests to be immediately available to all developers, so that developers know where to find them when needed. You also want an obstacle free environment with minimal overhead to writing new tests. Tests must also compile and execute quickly - project structure can play a part in all of this.
You may also want to consider that different levels of testing are possible, such as tests for unit, integration or UI automation. Segregating these types of tests is possible in some tools by using test categories, but sometimes it's easier for execution or reporting if they are separate libraries.
In small projects where there aren't a lot of projects, a 1:1 ratio is usually the preferred approach.
How to convert a list of strings to a single string in Unity (C#)
Since you are new to C# I would like to tell you that, you were trying to convert a list of strings to a single string. No it is not a list of string but it is a array of string. List of strings would be initalize like
List<string> SomeName = new List<string>();
Where as your one is declared as array. Now you can Join the Array of strings into one string as same as Javascript like
string SomeString = String.Join(",", kidIds);
The string.Join
method combines many strings into one. It receives two arguments: an array (or IEnumerable) and a separator string.
You can also create one string out of the String array using +
that would concatenate the strings like
string smstr = String.Empty;
for(int i=0; i<kidIds.Length; i++)
{
smstr = smstr + kidIds[i];
//or
smstr += kidIds[i]
}
You can also choose StringBuilder to create one string out of array of strings since StringBuilder.Append() method is much better than using the + operator like
StringBuilder sb = new StringBuilder();
for(int i=0;i<kidIds.Length;i++)
{
sb.Append(kidIds[i]);
}
But StringBuilder is good when the concatenations are less than 1000, String.Join() is even more efficient than StringBuilder.
Deserialization not filling data - C#
You should modify the code something like this
[XmlType("TRANSACTION_RESPONSE")]
public class TransactionResponse
{
[XmlElement("TRANSACTION")]
public BankQueryResponse Response { get; set; }
}
This will change like this
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
Deseralization Code would be something like this
TransactionResponse result = new TransactionResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(TransactionResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (TransactionResponse) serializer.Deserialize(xmlreader);
}
}
How to implement the keyboard key press in Windows Form Application
This might do the trick for you
However, a better way is probably to set your form's KeyPreview
property to true
, and then put your code into the form's keyDown
event (and set e.Handled = true as well, to prevent the key event from being passed on to whichever control does have the focus).
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.L)
{
//Do here
}
}
You would also like to view MSDN: Handle Keyboard Input at the Form Level which states about Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control.
Edit
WM_KEYDOWN: This message is posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
SendKeys: Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.
so when you receive signal from any device
System.Windows.Forms.SendKeys.Send("S");
and on keyDown
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.S)
{
//Shooting Code
}
else if (e.KeyCode == Keys.L)
{
//Some Other Code
}
}
and apart from that Programmatically generate keypress events in C#? will also give you an idea to implement your task
How to get all ip address in LAN?
This might do the trick for you
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if(!ip.IsDnsEligible)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// All IP Address in the LAN
}
}
}
}
The Only drawback of this code is that the information returned by instances of UnicastIPAddressInformation
is not available for operating systems earlier than Windows XP.
C# Case Sensitivity in Switch-statement
You can use ToUpper();
Like
Convert.ToChar(Console.ReadLine().ToUpper());
and to get saved from the error of getting more charaters with Console.ReadLine()
you can use
char grd = Convert.ToChar(Console.ReadKey().KeyChar.ToString().ToUpper());
How to get the cmd command output in c# to a lable
instead of process.WaitForExit();
do something like this
The complete code for your function would look something like this
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C ipconfig";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
while(!process.HasExited)
{
q += process.StandardOutput.ReadToEnd();
}
label1.text = q;
MessageBox.Show(q);
}
isset() is returning only true
PHP has different functions which can be used to test the value of a variable. Three useful functions for this are isset(), empty() and is_null(). All these function return a boolean value. If these functions are not used in correct way they can cause unexpected results.
isset() and empty() are often viewed as functions that are opposite, however this is not always true. In this post I will explain the differences between these functions.
isset()
isset — Determine if a variable is set and is not NULL
In other words, it returns true only when the variable is not null.
empty()
empty — Determine whether a variable is empty
In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
is_null()
is_null — Finds whether a variable is NULL
In other words, it returns true only when the variable is null. is_null() is opposite of isset(), except for one difference that isset() can be applied to unknown variables, but is_null() only to declared variables.
Instagram API hacked to allow uploads?
Per Instagram's API documentation:
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons...
While it is possible to use Instagram's private API to upload photos (you'd need to capture this information using a proxy server) it is a very quick way to get you instantly banned for life from using the API.
There are a handful of exceptions to this rule, Hipstamatic/Oggl being one of them. Whether or not posts.so is or not, I can't say, though I find it highly unlikely that they're authorized to do that they're doing. More-so with gramblr, their site is.. shady at best.
Enable/Disable Button When Listbox is Selected
You can use
IsEnabled="{Binding ElementName=ListBoxName, Path=SelectedItems.Count}"
to make it work.
Setting initial value of PasswordBox
You can read the Password from the file.
//Storing the Password in String.
string pwd = "Password Read from the file";
PasswordBox.Password = pwd;
So when the application is open for the first time and there would not be any password in the file it would show the empty PasswordBox. And again when the password has already been set by the user the Password will be found in the file and it would get loaded in the PasswordBox.
Value of a string for file's location is nil but a stored value says it isn't
There would be 2 solutions for the problem you are facing.
Get the Document in the
Document
Object not inPDFDocument
. And then probably try toSaveToFile
Something like thisDocument document = new Document(); //Load a Document in document Object document.SaveToFile("Sample.pdf", FileFormat.PDF);
You can use Stream for the same something like this
PdfDocument doc = new PdfDocument(); //Load PDF file from stream. FileStream from_stream = File.OpenRead(Loan_list[f]); //Make sure the Loan_list[f] is the complete path of the file with extension. doc.LoadFromStream(from_stream); //Save the PDF document. doc.SaveToFile(Loan_list[f] + ".pdf",FileFormat.PDF);
Second approach is the easy one, but I would recommend you to use the first one as for obvious reasons like document will give better convertability than stream. Since the document have section, paragraph, page setup, text, fonts everything which need to be required to do a better or exact formatting required.
How can I download emails from Gmail using C#/WinForms?
No you dont require to have Google API for getting(downloading) emails from Gmail account. You can read more about Reading Gmail Inbox Message
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
namespace mail
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Imap client = new Imap();
// connect to server
client.Connect("imap.gmail.com", 993, SslMode.Implicit);
// authenticate
client.Login("username", "password");
// select folder
client.SelectFolder("Inbox");
int NoOfEmailsPerPage = 10;
int totalEmails = client.CurrentFolder.TotalMessageCount;
// get message list - envelope headers
ImapMessageCollection messages = client.GetMessageList(ImapListFields.Envelope);
// display info about each message
foreach (ImapMessageInfo message in messages)
{
TableCell noCell = new TableCell();
noCell.CssClass = "emails-table-cell";
noCell.Text = Convert.ToString(message.To);
TableCell fromCell = new TableCell();
fromCell.CssClass = "emails-table-cell";
fromCell.Text = Convert.ToString(message.From);
TableCell subjectCell = new TableCell();
subjectCell.CssClass = "emails-table-cell";
subjectCell.Style["width"] = "300px";
subjectCell.Text = Convert.ToString(message.Subject);
TableCell dateCell = new TableCell();
dateCell.CssClass = "emails-table-cell";
if (message.Date.OriginalTime != DateTime.MinValue)
dateCell.Text = message.Date.OriginalTime.ToString();
TableRow emailRow = new TableRow();
emailRow.Cells.Add(noCell);
emailRow.Cells.Add(fromCell);
emailRow.Cells.Add(subjectCell);
emailRow.Cells.Add(dateCell);
EmailsTable.Rows.AddAt(2 + 0, emailRow);
}
int totalPages;
int mod = totalEmails % NoOfEmailsPerPage;
if (mod == 0)
totalPages = totalEmails / NoOfEmailsPerPage;
else
totalPages = ((totalEmails - mod) / NoOfEmailsPerPage) + 1;
}
}
}