Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

2013/10/02

[C#] Customize the delimiter of CSV when loading it by using Excel.Workbook.Open() (VBA)

I got an old program which can load a csv file and do something. The customer wants to change the delimiter from comma (,) to others like ";", "|", or "-"... etc. Sounds like an easy job. But no, it's not. The approach that uses on opening the csv file is
using Microsoft.Office;
....
xlsApp = new Excel.ApplicationClass();
xlsWBs = xlsApp.Workbooks;
xlsWB = xlsWBs.Open(TempFileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);

2013/07/15

Update app.config settings at runtime

using System.Configuration;

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;

appSettings["WorkingMinutes"].Value = numericUpDownWorkingPeriod.Value.ToString();
appSettings["RestMinutes"].Value = numericUpDownRestPeriod.Value.ToString();
appSettings["PhotoPath"].Value = textBoxPhotoPath.Text.Trim();

config.Save();
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);


Same as above, different style.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;

appSettings["key1"].Value = "value1";
appSettings["key2"].Value = "value2";

config.Save();
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

LINQ: Ways to have two filters.

string[] source = new string[5] { "12345", "1234", "45678", "6789", "6" };

// Method 1
var result1 = from o in source
where o.Length > 4 && o.StartsWith("1")
select o;
// Method 2
var result2 = from o in source
where (o.Length > 4 & o.StartsWith("1"))
select o;
// Method 3
var result3 = from o in source
where o.Length > 4
where o.StartsWith("1")
select o;
// Method 4
var result4 = source.Where(o => o.Length > 4).Where(o => o.StartsWith("1"));

Different style:
string[] source = new string[5] { "12345""1234""45678""6789""6" };

// Method 1
var result1 = from o in source
              where o.Length > 4 && o.StartsWith("1")
              select o;
// Method 2
var result2 = from o in source
              where (o.Length > 4 & o.StartsWith("1"))
              select o;
// Method 3
var result3 = from o in source
              where o.Length > 4
              where o.StartsWith("1")
              select o;
// Method 4
var result4 = source.Where(o => o.Length > 4).Where(o => o.StartsWith("1"));

2013/05/14

[TextBox, DataGridView, BindingSource] Search as you type

I created my own search as you type feature by using TextBox, DataGridView, and BindingSource. It's very simple to implement. Here is the code:

PS: I already have a TextBox & a DataGridView on the form.

public partial class LookupTable : Form
{
  // This will be the data source of the DataGridView.
  BindingSource oBindingSource = new BindingSource();
  CallerDTO caller = null;
 
  public LookupTable(DataTable sourceData, CallerDTO sourceDTO)
  {
    InitializeComponent();
    caller = sourceDTO;
 
    // Assign the DataTable to our BindingSource object.
    oBindingSource.DataSource = sourceData;
  }
 
  private void LookupTable_Load(object sender, EventArgs e)
  {
    toolTipFind.SetToolTip(textBoxFind, "You can search by Name or by Code.");
 
    // Assign the BindingSource object to the DataGridView.
    dataGridViewResult.DataSource = oBindingSource;
  }
 
  private void textBoxFind_TextChanged(object sender, EventArgs e)
  {
    TextBox oTextBox = sender as TextBox;
 
    // Here is the key of the whole "Search As You Type" function.
    oBindingSource.Filter = "NAME LIKE '%" + oTextBox.Text + "%' OR CODE LIKE '%" + oTextBox.Text + "%'";
  }
 
  private void dataGridViewResult_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
  {
    // Here I need to send back the value that user clicked on.
    caller.StringResult = dataGridViewResult.Rows[e.RowIndex].Cells[1].Value.ToString();
 
    // This is just a public method for me to do something after user clicking.
    caller.CallerLoad();
    this.Close();
  }
}

Result:

2013/03/04

[C#] Dynamically load assembly (dll)

using System.Reflection;
using IterfaceLibrary;
 
IModuleInfo clientForm = null;
Form clientForm2 = null;
string formID = String.Empty;
Assembly newDll = Assembly.LoadFrom("Test.dll");
 
foreach (Type itemType in newDll.GetTypes())
{
  if (itemType.IsClass)
  {
    if (itemType.FullName.Contains("Form"))
    {
      // Assembly有implement Interface
      clientForm = Activator.CreateInstance(itemType) as IModuleInfo;
      MessageBox.Show(clientForm.ModuleName);
      clientForm.ShowForm(this, "From Main");

      // Assembly沒有implement Interface
      clientForm2 = Activator.CreateInstance(itemType) as Form;
      // 呼叫clientForm2裡面的ShowModuleID()方法,該方法回傳formID字串
      formID = itemType.InvokeMember("ShowModuleID", BindingFlags.InvokeMethod, null,
        clientForm2, null) as string;
      MessageBox.Show(formID);
    }
  }
}

2013/01/15

Allowing only digitals in textbox

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
    e.Handled = true;
}

Reference: stackoverflow - How do I make a textbox that only accepts numbers?

2012/11/29

Delete a specific DataRow from the DataTable

DataTable dt = BusinessLogic.GetTable(sqlCmd);
dt.Rows.Remove(dt.Select("ColumnName1 = '12345' and ColumnName2 = '67890'")[0]);
dt.AcceptChanges();

2012/10/08

WebClient.DownloadString()

I just want to check a web content has something I want or not, so I use the WebClient.DownloadString() instead of using HttpWebRequest, HttpWebResponse, StreamReader... etc.
using (WebClient wclient = new WebClient())
{
    wclient.Encoding = Encoding.UTF8;   // change to fit your environment
    string content = wclient.DownloadString(url);
    result = content.Contains(keyword);
}

2012/08/13

Add parameters in oledb and odbc CommandText

OleDb:
using (OleDbCommand cmd = new OleDbCommand())
{
  cmd.CommandText = "Select * from VIP where ID = ? And RegDate >= ?";
  cmd.Parameters.AddWithValue("id", id);
  cmd.Parameters.AddWithValue("regDate", regDate);
  using (OleDbDataReader reader = cmd.ExecuteReader())
  {
    // ..........
  }
}
Odbc:
using (OdbcCommand cmd = new OdbcCommand())
{
  cmd.CommandText = "Select * from VIP where ID = ? And RegDate >= ?";
  cmd.Parameters.Add("id", OdbcType.Int).Value = id;
  cmd.Parameters.Add("regDate", OdbcType.DateTime).Value = regDate;
  using (OdbcDataReader reader = cmd.ExecuteReader())
  {
    // ..........
  }
}

1. The name of parameter doesn't matter, but the order of parameter does.
2. I didn't include full codes here so don't forget to fill in other components like OleDbConnection or OdbcConnection.

2012/08/06

Trapping F9 in Winform

private void Form2_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.F9)
  {
    // your work here...
  }
}

1. Use the KeyDown event to trap it.
2. Set the Form's KeyPreview property to True.

2012/04/12

Force to show Exception in English

using System.Threading;
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

Reference: 如何強迫 .Net 應用程式輸出英文的例外訊息

2012/02/16

[C#] Android C2DM

internal static bool sendAndroidNotification(string message, string registrationID)
{
    const String ClientLoginURL = @"https://www.google.com/accounts/ClientLogin";
    const String C2DMServerURL = @"http://android.apis.google.com/c2dm/send";
    string collapseKey = DateTime.Now.ToShortDateString();

    String AuthTokenParams =
        @"accountType=GOOGLE&Email=" + Properties.Settings.Default.AndroidSenderEmail   // your sender email
        + "&Passwd=" + Properties.Settings.Default.AndroidSenderPassword    // your sender password
        + "&service=ac2dm";
    string authToken = getAndroidAuthToken(ClientLoginURL, AuthTokenParams);

    Dictionary<stringstring> data = new Dictionary<stringstring>();
    data.Add("data.msg"HttpUtility.UrlEncode(message));  // use UrlEncode() so that I can push messages other than English (like Chinese)

    return sendAndroidPushMessage(C2DMServerURL, registrationID, collapseKey, authToken, data);
}

2012/02/08

byte[] convert to hexadecimal string (and vice versa)

byte[] to hex string:
static string ByteArrayToString1(byte[] source)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte item in source)
    {
        sb.AppendFormat("{0:x2}", item);
    }
    return sb.ToString();
}

static string ByteArrayToString2(byte[] source)
{
    return BitConverter.ToString(source).Replace("-""");
}

static string ByteArrayToString3(byte[] source)
{
    // namespace: System.Runtime.Remoting.Metadata.W3cXsd2001
    return new SoapHexBinary(source).ToString();
}

static string ByteArrayToString4(byte[] source)
{
    // works for .Net 4 only
    return String.Concat(Array.ConvertAll(source, x => x.ToString("X2")));
}

Loop through enum

enum Week
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}
foreach (Week item in Enum.GetValues(typeof(Week)))
{
    //...
}

Reference: Can You Loop Through All Enum Values? c#

2012/01/17

IPv4 Address convert to Integer (and reverse) (updated)

static Int64 IPv4StringToInt64(string ipv4String)
{
    Int64 ipInteger = 0;
    try
    {
        ipInteger = (long)(uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipv4String).GetAddressBytes(), 0));
    }
    catch (Exception)
    { }

    return ipInteger;
}
static string IPv4Int64ToString(Int64 ipv4Int64)
{
    if (ipv4Int64 < 0)
        return "0.0.0.0";
    else if (ipv4Int64 < 4294967295)
        return IPAddress.Parse(ipv4Int64.ToString()).ToString();
    else
       return "255.255.255.255";
}
Usage:
Console.WriteLine("255.255.255.0 => " + IPv4StringToInt64("255.255.255.0"));
Console.WriteLine("4294967040 => " + IPv4Int64ToString(4294967040));

Reference: stackoverflow - How to convert an IPv4 address into a integer in C#?

2011/06/14

Refresh WebBrowser in Winform

I put a WebBrowser control on my form and use it to load XML files. Here is the code:
OpenFileDialog FileDialog = new OpenFileDialog();
FileDialog.Title = "Open XML Document";
FileDialog.Filter = "XML file (*.xml)|*.xml";

if (FileDialog.ShowDialog() == DialogResult.OK)
{
 WebBrowser1.Navigate(FileDialog.FileName);
 WebBrowser1.Refresh();
}
I found that if I load the second XML, sometimes it will not refresh itself to show the new XML content. Instead, it still shows the previous one. I google the web to see if there is any other way to prevent the cache. Unfortunately, I found nothing. But this post inspires me and so I create a workaround.

2011/05/24

Integrated the EasyAlgo FlashUpload control into the ASP.Net web application

Updated (2012.10.31):
I've removed this article due to this.

FlashUpload flash control to manage user uploads. It is a very powerful flash control that can let you customize the control. The price is affordabile (or you can try it free without limitations), and their customer service is outstanding. I use google talk to chat with them when I encounter any problem (also request some features!) with no problem.

OK, no more advertisement. :) Below is an example of what I've done for customizing it. The reason I put a blog here is because their document is good but not organized very well. I spent lots of time on puting things together... You can select many ways to integrate the flash control into your web app. Here I choose javascript.

2011/02/26

Simple file upload by using FileUpload control.

What I need:
1.User can upload only one file at a time.
2.No save file to disk; read it's content and then dispose it.
3.Only txt and csv file types are allowed.

Here is the aspx page
<asp:Panel ID="PanelUploadList" runat="server" ViewStateMode="Disabled">
    <hr />
    Please select a text file to upload:
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorFileUpload" runat="server"
        ControlToValidate="FileUpload1"
        ErrorMessage="Please select a file to upload!" Display="Dynamic">*asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="RegularExpressionValidatorFileUpload" runat="server"
        ControlToValidate="FileUpload1" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.txt|.csv)$"
        ErrorMessage="Only txt and csv file types are allowed!">*asp:RegularExpressionValidator>
    <asp:Button ID="ButtonUpload" runat="server" OnClick="ButtonUpload_Click"
        Text="Upload" />
    <hr />
</asp:Panel>

2011/01/21

Sort ListBox items (ascending/descending)

1. Create a class that implements IComparer<T> interface.
private class SortListItem : IComparer<ListItem>
{
    public int Compare(ListItem x, ListItem y)
    {
        return String.Compare(x.Value, y.Value);
    }
}

DateTime: Get the first date of the week

1. Create an extension method.
public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }
}