Infolink

 

Search This Blog

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"

Mar 7, 2014

Table with fixed header on scroll

Column 1 Column 2 Column 3
Row A-1 Row A-2 Row A-3
Row B-1 Row B-2 Row B-3
Row C-1 Row C-2 Row C-3
Row D-1 Row D-2 Row D-3
Row E-1 Row E-2 Row E-3
Row F-1 Row F-2 Row F-3
Row G-1 Row G-2 Row G-3

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 6, 2014

Difference between CTE and Temp Table

CTE

  • CTE is  un-materialized/ non-indexable (cannot create indexes on CTE)
  • CTE is logical/disposableView
  • CTE persists only till the very next query
  • CTE cannot have constraints
  • CTE is mostly used for recursion, as CTE can call itself
  • CTE resists in memory
 Example 

By using CTE

    ;With CTE1(Addr, FullName, Age)
    AS
    (
    SELECT Addr.Addr, Emp.FullName, Emp.Age from Address Addr
    INNER JOIN Employee Emp ON Emp.EID = Addr.EID
    )
    SELECT * FROM CTE1 --Using CTE
    WHERE CTE1.Age > 50
    ORDER BY CTE1.FullName

Temp Table

  • Temp table gets stored in temp table
  • Temp table persists till the current connection ends
  • Temp table can be referred in sub procedure
  • Temp table can have constraints,indexes and primary defined
  • Indexes can be implemented in Temp Table
  • Data can be updated in Temp Table
  • Temp Tables are stored in disk
Example
Temp Table

    CREATE TABLE #Temp
    (
    UID int,
    FullName varchar(50),
    Addr varchar(150)
    )
    GO
    insert into #Temp values ( 1, 'Raj','Pune');
    GO
    Select * from #Temp 

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 31, 2014

ROW_NUMBER() in SQL

Hello guys,

i have make a simple application which contains A Gridview with the thousend of records.
so i am manage it with paging.

IF I WANT TO FILTER GRIDVIEW RECORDS WITH SQL ?

So, i have take two textbox two filtering the gridview as follow.

and i am sending the value in the database as follow.

create table #tmp (id int,name varchar(10))

insert into #tmp values(1,'a')

insert into #tmp values(2,'b')
insert into #tmp values(3,'c')
insert into #tmp values(4,'d') 

select id,name,rownumber,totalrowcnt from
(
    select #tmp.*,ROW_NUMBER() over (order by #tmp.id) rownumber,count(*) over() totalrowcnt
    from #tmp
) result
where result.rownumber between VALUE1 and VALUE2
* here value1 and value2 are textbox value.

So, with this simple SQL query i can filter the gridview records.

Jan 22, 2014

Prevent self closing html tags in .NET

I create an input element, it will self close. How can I prevent this?

<asp:TextBox id="txt1" runat="server"></asp:TextBox
SOLUTION
  1. Tools
  2. Options
  3. Text Editor
  4. HTML
  5. Formatting
  6. Uncheck the box for Auto insert close tag

Jan 21, 2014

Set the tab order in VB.NET

I have a bunch of buttons on a form and when the person presses TAB I want the focus of the controls move in a specific order.

solution :

If you have form with lots of control then manage tab index by below method:
  •     Open form in design mode.
  •     Click on “View” from toolbar --> “Tab Order” at bottom.

Example:




Then just click on controls one by one in order that you want to set tab order.

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));

How to connect to an external SQL server database in ASP.NET / VB.NET

Connecting to databases in .NET is different if you are coming from other languages such as PHP. To connect to a database in ASP.NET / .NET in general, you use "Connection Strings" that essentially is the connection information to the database.

First and foremost, in your code behind file within an ASP.NET application (or simply the .vb or .cs file of your .NET desktop application), you will need to first import the namespace that has the relevant database-related classes and methods, etc.

Note: All examples use the Visual Basic language, but the concept is the same for both Visual Basic and C#, for example.

Jan 11, 2014

DateTimePicker ValueChanged and CloseUp Event

some time ago i come to know this problem in my form When the month forward or backward arrow is clicked on my DateTimePicker control it repeatedly fires the ValueChanged event.


I have solve this problem using Closeup event of DatepTimePicker

ValueChanged Event

DateTimePicker ValueChanged Event repeats with month/year arrow

VB.NET


Private Sub datepicker_ValueChanged (sender As Object,e As EventArgs) Handels datepicker.ValueChanged MessageBox.Show("You are in the DateTimePicker.ValueChanged event.")

CloseUp Event


when the user changes the value manually, the CloseUp event obviously isn't triggered

VB.NET
Private Sub datepicker_CloseUp(sender As Object,e As EventArgs) Handels datepicker.CloseUp

MessageBox.Show("You are in the DateTimePicker.CloseUp event.")
Related Posts Plugin for WordPress, Blogger...