Infolink

 

Search This Blog

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

Apr 22, 2014

c# - Convert comma separated string to array

Split separates strings. Often strings have delimiter characters in their data. Split handles splitting upon string and character delimiters.Methods can be combined. Using IndexOf and Substring together is another way to split strings.
e.g.
Use Split to separate parts from a string. If your input is "A B C", split on the space to get an array of "A", "B" and "C".
<

string str = "1,2,3,4";

        // 1st way
        string[] strArray = str.Split(new char[] { ',' });
        int[] intArray = new int[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
        {
            intArray[i] = int.Parse(strArray[i]);
        }

        // 2nd way
        string[] array = str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

Apr 5, 2014

contextual help dialogs using HelpProvider Class

The HelpProvider control offers contextual help dialogs. Sometimes a user wants a verbose description of a control. With HelpProvider we provide this description by adding a Help button and setting some properties.

using System;
using System.Drawing;
using System.Windows.Forms;

How to extract a portion of a string variable in C#

There are many ways to do this, i am exaplaining two of them.


1. String.Remove Method (Int32, Int32)

Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Syntax :

public string Remove(
    int startIndex,
    int count
)
example :

My string is "C:\Program Files\Microsoft Visual Studio\VSS\users" and i want to

"C:\Program Files\Microsoft Visual Studio\VSS" then

    string s = "svn://mcdssrv/repos/currecnt/class/MBackingBean.java";
    s.Remove(s.LastIndexOf('\'));
2. String.Substring Method

Retrieves a substring from this instance.

Substring takes the start index (zero-based) and the number of characters you want to copy.

example :
   

string str = "C:\Program Files\Microsoft Visual Studio\VSS\users";
    str = str.Substring(0, str.LastIndexOf('\') + 1);

3. By using both method

    var subString = "C:\Program Files\Microsoft Visual Studio\VSS\users";
        subString = subString.Remove(subString.LastIndexOf('\')+1);

Mar 25, 2014

How to Display the Actual Number with Decimal

When you configure how numbers display, you select the number of decimal places to show. Crystal Reports then rounds the display value to that decimal position and that is what you see. 

But what if you want to display the actual number? If the original number has no decimal places, you want to see that. If the original has three decimal places, you want to see all three.

You can do this using conditional formatting.

Mar 21, 2014

ToText Function in Crystal Report

ToText Function

Uses

The ToText function can be used to convert number, date, boolean, or time values to a string (text). It provides you with controls that let you control how the resulting string looks.
It’s mostly used for concatenation (for example, you can create a title for your report that shows the records covered, or a group name that shows the date range included.)
  • Add parameters to a Report title
  • Control how group names appear (you can force your dates to appear in the format 3/7/10 or 20100901.
  •  

List of FUNCTIONS in Crystal Report

Crystal Reports provides many FUNCTIONS for extracting information from the files. 

List of Functions

  • Abs(x)
  • Average([array])
  • Average(field, condField)
  • Average(field, condField, "condition")
  • Average(field)
  • BeforeReadingRecords
  • Count([array])
  • Count(field, condField)
  • Count(field, condField, "condition")
  • Count(field)
  • Date (yyyy, mm, dd)
  • Day (x)
  • DayOfWeek (x)
  • GroupNumber
  • IsNull
  • Length(x)
  • LowerCase (x)
  • Maximum([array]) Maximum(field, condField)
  • Maximum(field, condField, "condition")
  • Maximum(field)
  • Minimum([array])
  • Minimum(field, condField)
  • Minimum(field, condField, "condition")
  • Minimum(field)
  • Month (x)
  • Next
  • NextIsNull
  • NumericText(fieldname)
  • PageNumber
  • PopulationStdDev([array])
  • PopulationStdDev(field, condField)
  • PopulationStdDev(field, condField, "condition")
  • PopulationStdDev(field)
  • PopulationVariance([array])
  • PopulationVariance(field, condField)
  • PopulationVariance(field, condField, "condition")
  • PopulationVariance(field)
  • Previous
  • PreviousIsNull
  • PrintDate
  • RecordNumber
  • Remainder(numerator, denominator)
  • ReplicateString(x,n)
  • Round(x, # places)
  • Round(x)
  • StdDev([array])
  • StdDev(field, condField)
  • StdDev(field, condField, "condition")
  • StdDev(field)
  • Sum([array])
  • Sum(field, condField)
  • Sum(field, condField, "condition")
  • Sum(field)
  • Today
  • ToNumber (x)
  • ToText (x, # places)
  • ToText (x)
  • ToWords(x, # places)
  • ToWords(x)
  • TrimLeft (x)
  • TrimRight (x)
  • Truncate (x)
  • UpperCase (x)
  • Variance([array])
  • Variance(field, condField)
  • Variance(field, condField, "condition")
  • Variance(field)
  • WhilePrintingRecords
  • WhileReadingRecords
  • Year (x)

Mar 19, 2014

Date field in the format of D D M M Y Y Y Y in Crystal Report

The default format gives me the date as ddmmyyyy I need to figure out a way to print the date in the format of D D M M Y Y Y Y.

 


To achieve this i need create a new formula field.

Now lets look at the formula.

totext({YourDateFieldHere}, "ddmmyyyy")

Then create a new formula and paste the following

mid({@formulaDate},1,1)&" "&mid({@formulaDate},2,1)&"
"&mid({@formulaDate},3,1)&" "&mid({@formulaDate},4,1)&"
"&mid({@formulaDate},5,1)&" "&mid({@formulaDate},6,1)&"
"&mid({@formulaDate},7,1)&" "&mid({@formulaDate},8,1)

explanation for mid function

Local StringVar x :=totext(Currentdate, "
ddmmyyyy")
Local StringVar y;

//Start at position 2, go to the end of the string

y := Mid (x, 2); //y is now "9032014"

//Start at position 2, extract 1 character

y := Mid (x, 2, 1) //y is now "9"

Feb 22, 2014

Overloading and Overriding in C# with real world example

In my early day career in many interviews I asked same question, what is overloading and overriding so decided to write this small article which may help someone. We will see here in detail about the overloading, overriding and then differences between them.

Overloading: is the mechanism to have more than one method with same name but with different signature (parameters). A method can be overloaded on the basis of following properties

  1.     Have different number of parameter
  2.     Having same number of parameters but of different type
  3.     Having same number and type of parameters but in different orders

Feb 5, 2014

Dynamically Changing Master Pages

Suppose we have two Master pages and we want to change them dynamically.

Let the style sheet are:

  1.     blue.master - set background color to Blue
  2.     green.master - set background color to Green
I have added a page with a dropdownlist which list the master pages as option and in the code behind as drop down list selected index changed event response we saved the user selection in the session and in the Page_PreInit event we changed the master page dynamically.

Feb 4, 2014

AsyncPostBackTrigger vs PostBackTrigger with example

In the <triggers> template in an update panel, there are the options of an AsyncPostBackTrigger or a PostBackTrigger. By default, controls outside of an update panel will trigger a normal synchronous post back. The AsyncPostBackTrigger “wires” up these controls to trigger an asynchronous post back. Conversely, controls declared inside an update panel will trigger an asynchronous call by default. The PostBackTrigger short circuits this, and forces the control to do a synchronous post back. Utilizing a simple “time” example:

Jan 12, 2014

C# Event Handlers and Delegates in ASP.Net with Web User Controls

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).


This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Polymorphisms in C++

When people talk about polymorphism in C++ they usually mean the thing of using a derived class through the base class pointer or reference, which is called subtype polymorphism. But they often forget that there are all kinds of other polymorphisms in C++, such as parametric polymorphism, ad-hoc polymorphism and coercion polymorphism.

These polymorphisms also go by different names in C++,

Subtype polymorphism is also known as runtime polymorphism.
Parametric polymorphism is also known as compile-time polymorphism.

Ad-hoc polymorphism is also known as overloading. 
Coercion is also known as (implicit or explicit) casting.

Creating dynamic textbox

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add Textbox" />

        <asp:Panel ID="Panel1" runat="server" >

       

        </asp:Panel>           

        </div>

    </form>

</body>

</html>


C#


using System;

using System.Web.UI.WebControls;

using System.Collections.Generic;

namespace WebApplication1

{

    public partial class _Default : System.Web.UI.Page

    {

        private List textboxes;
        protected void Page_Load(object sender, EventArgs e)
        {
            PreRender += new EventHandler(_Default_PreRender);
            textboxes = new List();

            if(IsPostBack)
            {
                //recreate Textboxes
                int count = Int32.Parse(ViewState["tbCount"].ToString());

                for (int i = 0; i < count; i++)
                {
                    TextBox tb = new TextBox();
                    tb.ID = "tb" + i;
                    Panel1.Controls.Add(tb);
                    textboxes.Add(tb);
                    tb.Text = Request.Form[tb.ClientID];
                }

            }

        }      

        protected void Button1_Click(object sender, EventArgs e)
        {
            //create new textbox

            TextBox tb = new TextBox();
            tb.ID = "tb" + textboxes.Count;
            Panel1.Controls.Add(tb);
            textboxes.Add(tb);
        }

        void _Default_PreRender(object sender, EventArgs e)
        {
            //remember how many textboxes we had
            ViewState["tbCount"] = textboxes.Count;
        }
    }
}
 

------------

private System.Windows.Forms.TextBox[] textboxes;

textboxes = new System.Windows.Forms.TextBox[2];

int cnt=0;

foreach (System.Windows.Forms.TextBox textbox in textboxes)
{
      // the location on the form. you may need to play with this

      // and it should change for each textbox

      textbox.Location = new System.Drawing.Point(88, 50);

      textbox.Name = "textbox"+cnt.ToString();

      textbox.Size = new System.Drawing.Size(173, 20);

      textbox.TabIndex = cnt;

      textbox.Visible = true;

      cnt++;
}


--------------

public partial class AGEP : IdealFramework.UI.Screen
{

TextBox[] TB1 = new TextBox[18];

public AGEP()
{
InitializeComponent();
}
private void AGEP_Load(object sender, EventArgs e)
{
int sub = 0;
int sub2 = 0;
while (sub < 18)
{
TB1[sub] = new TextBox();
sub2 = sub * 25 + 1;
TB1[0].Location = new Point(5, sub2);
pnlPmtArea.Container.Add(TB1[sub]);
sub++;
}
}

Instantly Increase ASP.NET Scalability


Each time a request for a .NET resource (.aspx, page, .ascx control, etc.) comes in a thread is grabbed from the available worker thread pool in the asp.net worker process (aspnet_wp.exe on IIS 5.x, w3wp.exe on IIS 6/7) and is assigned to a request. That thread is not released back into the thread pool until the final page has been rendered to the client and the request is complete.

Performance Optmization with .NET

I have a web service, so the handler is called multiple times concurrently all the time.

Inside I create SqlConnection and SqlCommand. I have to execute about 7 different commands. Different commands require various parameters, so I just add them once:

command.Parameters.Add(new SqlParameter("@UserID", userID));
command.Parameters.Add(new SqlParameter("@AppID", appID));
command.Parameters.Add(new SqlParameter("@SID", SIDInt));
command.Parameters.Add(new SqlParameter("@Day", timestamp.Date));
command.Parameters.Add(new SqlParameter("@TS", timestamp));

Dec 19, 2013

How to send an image with this customized C# Mail function?

C# Mail Function:

    /*For sending an email notification to the new user*/
        protected void SendNotificationByEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
        {
            SmtpClient sc = new SmtpClient("MailServer");
            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("Test@MailServer.com", "Test System)");


                msg.Bcc.Add(toAddresses);
                msg.Subject = MailSubject;
                msg.Body = MessageBody;
                msg.IsBodyHtml = isBodyHtml;
                sc.Send(msg);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        protected void Send(string username)
        {
            string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";

            string networkID = username.ToString();
            using (SqlConnection conn = new SqlConnection(connString))
            {
                var sbEmailAddresses = new System.Text.StringBuilder(2000);

                //initiate the varibles
                string name = null;

                // Open DB connection.
                conn.Open();

                string cmdText2 = @"SELECT     Name
                                    FROM       dbo.employee
                                    WHERE     (Username = @networkID)";
                using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
                {
                    cmd.Parameters.AddWithValue("@networkID", networkID);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader != null)
                    {
                        if (reader.Read())
                        {
                            name = reader["Name"].ToString();
                            sbEmailAddresses.Append(username).Append("@mailServer.com");
                        }
                    }

                    //var sEMailAddresses = sbEmailAddresses.ToString();
                    string body = @"Good day "
                                    + name +
                                    @", <br /><br />
                                    You have been added to the <a href='http://localhost/TestSys'>Test</a>.
                                    <br /><br />
resources.
                                    </b> <br /> <br />
                                    <img src='images/Admin/EmailNotification.jpg' alt=' Message'/>

                string imagePath = Server.MapPath("~") + "\\";
                string fileName = imagePath + "EmailNotification.jpg";
                AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html)
                LinkedResource linkedRes = new LinkedResource(fileName);
                linkedRes.ContentId = "image1";
                linkedRes.ContentType.Name = fileName;
                av.LinkedResources.Add(linkedRes);


                SendNotificationByEmail(sbEmailAddresses.ToString(), "", "Welcome", body, true);
                sbEmailAddresses.Clear();
                reader.Close();
                }

                conn.Close();
            }
}

Nov 30, 2012

ArrayList in Asp.net

The ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.

The following code creates a new ArrayList object named books and three items are added:
  ArrayList books = new ArrayList();
  books.Add(”book1");
  books.Add(”book2");
  books.Add(”book3");

Nov 7, 2012

Using Settings in C#

Introduction

The .NET Framework 2.0 allows you to create and access values that are persisted between application execution sessions. These values are called settings. Settings can represent user preferences, or valuable information the application needs to use. For example, you might create a series of settings that store user preferences for the color scheme of an application. Or you might store the connection string that specifies a database that your application uses. Settings allow you to both persist information that is critical to the application outside of the code, and to create profiles that store the preferences of individual users.

While Visual Basic 2005 has provided an easily discoverable mechanism for accessing settings using the My namespace, there is no analogous namespace in Visual C# 2005, and thus settings are somewhat more difficult to access. Nonetheless, C# users can still use settings by accessing the Properties namespace. In the course of this article, you will learn the difference between application and user settings, how to create new settings at design time, how to access settings at run time, and even how to incorporate multiple sets of settings into your application.

Nov 5, 2012

How to create a countdown timer application using C# and WinForms

In this tutorial I will explain how to create a countdown application in C#. For this application I did not declare any additional namespaces.

StatusBar in c# Windows Application

StatusBar Example

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace StatusBarExample
{
  /// <summary>
  /// Summary description for StatusBarExample.
  /// </summary>
  public class StatusBarExample : System.Windows.Forms.Form
  {
    internal System.Windows.Forms.StatusBar statusBar;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    public StatusBarExample()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.statusBar = new System.Windows.Forms.StatusBar();
      this.SuspendLayout();
      //
      // statusBar
      //
      this.statusBar.Location = new System.Drawing.Point(0, 138);
      this.statusBar.Name = "statusBar";
      this.statusBar.ShowPanels = true;
      this.statusBar.Size = new System.Drawing.Size(292, 24);
      this.statusBar.SizingGrip = false;
      this.statusBar.TabIndex = 1;
      //
      // StatusBarExample
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
      this.ClientSize = new System.Drawing.Size(292, 162);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.statusBar});
      this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.Name = "StatusBarExample";
      this.Text = "StatusBar Example";
      this.Load += new System.EventHandler(this.StatusBarExample_Load);
      this.ResumeLayout(false);

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.Run(new StatusBarExample());
    }

    private void StatusBarExample_Load(object sender, System.EventArgs e)
    {
      StatusBarPanel pnlStatus = new StatusBarPanel();
      pnlStatus.Text = "Ready";
      pnlStatus.Icon = new Icon(Application.StartupPath + "\\active.ico");
      pnlStatus.AutoSize = StatusBarPanelAutoSize.Contents;

      StatusBarPanel pnlConnection = new StatusBarPanel();
      pnlConnection.Text = "Connected to " + "localhost";
      pnlConnection.AutoSize = StatusBarPanelAutoSize.Spring;

      statusBar.Panels.Add(pnlStatus);
      statusBar.Panels.Add(pnlConnection);

    }
  }
}

Related Posts Plugin for WordPress, Blogger...