Threading

Visit: https://zonixsoft.com

C# supports parallel execution of code through multithreading. A thread is an independent execution path, able to run simultaneously with other threads.A C# program starts in a single thread created automatically by the CLR and operating system (the “main” thread), and is made multi-threaded by creating additional threads.The CLR assigns each thread its own memory stack so that local variables are kept separate.

Threading enables your C# program to perform concurrent processing so you can do more than one operation at a time. The System.Threading namespace provides classes and interfaces that support multithreaded programming and enable you to easily perform tasks such as creating and starting new threads, synchronizing multiple threads, suspending threads, and aborting threads. The advantage of threading is the ability to create applications that use more than one thread of execution.

How Threading Works

Multithreading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system. A thread scheduler ensures all active threads are allocated appropriate execution time, and that threads that are waiting or blocked – for instance – on an exclusive lock, or on user input – do not consume CPU time.

On a single-processor computer, a thread scheduler performs time-slicing – rapidly switching execution between each of the active threads.

On a multi-processor computer, multithreading is implemented with a mixture of time-slicing and genuine concurrency – where different threads run code simultaneously on different CPUs. It’s almost certain there will still be some time-slicing, because of the operating system’s need to service its own threads – as well as those of other applications.

Killing a Thread:

We can kill a thread by calling the

 

Abort method of the thread.

MyThread.Abort();

Suspend and Resuming Thread:

We can suspend the execution of a thread and once again start its execution from another thread using the Thread object’s Suspend and Resume methods.

  MyThread.Suspend() // causes suspend the Thread Execution.

 

  MyThread.Resume() // causes the suspended Thread to resume its execution.

 

 

Creating and Starting Threads

Threads are created using the Thread class’s constructor, passing in a ThreadStart delegate – indicating the method where execution should begin.  Here’s how the ThreadStart delegate is defined:

public delegate void ThreadStart();

Calling Start on the thread then sets it running. The thread continues until its method returns, at which point the thread ends. Here’s an example, using the expanded C# syntax for creating a TheadStart delegate:

class ThreadTest {

  static void Main() {

    Thread t = new Thread (new ThreadStart (Go));

    t.Start();   // Run Go() on the new thread.

    ……

  }

  static void Go() { …..}

A thread can be created more conveniently using C#’s shortcut syntax for instantiating delegates:

static void Main() {

  Thread t = new Thread (Go);    // No need to explicitly use ThreadStart

  t.Start();

 

}

static void Go() { … }

In this case, a ThreadStart delegate is inferred automatically by the compiler. Another shortcut is to use an anonymous method to start the thread:

static void Main() {

  Thread t = new Thread (delegate() { Console.WriteLine (“Hello!”); });

  t.Start();

}

A thread has an IsAlive property that returns true after its Start() method has been called, up until the thread ends.A thread, once ended, cannot be re-started.

Some very special features of crystal reports

Visit: .comhttp://www.zonixsoft

Create a Watermark

A watermark is a graphical or textual element that is placed behind the rest of yourreport. Examples of useful watermarks are your company logo, the word “Draft,”or other items that you may want to appear right behind the rest of the elements of your report.

 

1. Open the report you wish to add the watermark to. Ensure that the Designtab is selected.

2. Position your mouse over the gray Page Header section name. Right-click.

3. Choose Insert Section Below from the pop-up menu. This will insert a second page header section (you’ll now see Page Header a and Page Header b).

4. Insert the graphic or text you want to appear behind the rest of the report into Page Header b (it’s helpful if the graphic has been lightened with a graphic editing program, or if the text is formatted with a light shade of font color).

5. If you want the watermark to appear more toward the vertical center of the page, make Page Header b taller and move the graphic or text farther down in the section.

6. If you want to repeat the watermark more than once on a page, insert it into Page Header b several times, or copy and paste the original item several times in Page Header b.

7. Position your mouse over the gray Page Header b section name. Right-click.

8. Choose Format Section from the pop-up menu in Crystal Reports 8.5, or Section Expert from the pop-up menu in Crystal Reports 9. This will display the Section Expert.

9. Choose the Underlay Following Sections check box for Page Header b in the Section Expert. Click OK to close the Section Expert.

10. If you wish to underlay items in the existing Page Header a section (field titles, the report title, and so forth), swap Page Header b and Page Header a by holding your mouse button down on either gray page header section name. When the mouse cursor changes to the hand icon, drag and drop the page header on top of the other page header. The sections will swap.

 

Change Graphics According to a Condition

Crystal Reports features the capability to format report objects (database fields, formulas, text objects, and so forth) conditionally, depending on the contents of a field, formula, or other condition. However, you may wish to actually insert several different graphic or picture files on your report and display them only when a certain condition occurs.

 

1. Open or create the report that you wish to add multiple conditional graphics to.

2. Add as many graphics to the report as are required. For example, if you want to display “thumbs up” and “thumbs down” graphics, add both graphic files to the report.

3. Place the graphics side by side, so that you may select each graphic individually.

4. Select the first graphic by clicking on it. Right-click. From the pop-up menu, select Format Graphic. The Format Editor will appear.

5. Select the Common tab. Next to the Suppress check box, click the Conditional Formula button. The Format Formula Editor will appear.

6. Add a Boolean formula to conditionally suppress the graphic. For example, to suppress the graphic if Last Year’s Sales is less than $50,000, enter a formula similar to this:

{Customer.Last Year’s Sales} < 50000

7. Click the Save button to close the Format Formula Editor. Click OK to close the Format Editor.

8. Repeat steps 4–7 for the remaining graphics, using “mutually exclusive” condition formulas, so that only one graphic at a time will display. For example, to suppress another graphic if Last Year’s Sales is greater than or equal to $50,000, enter a formula similar to this:

{Customer.Last Year’s Sales} >= 50000

9. Select each graphic and place it on top of the others, so that all graphics are placed in the same position. Because of the “mutually exclusive” conditional formatting, only one will appear at a time when the report is displayed.

 

Use WingDings and Other Symbol Fonts

By default, Crystal Reports uses a particular font face and size for report objects. While you can change the default font choices in the File | Options dialog box, you can also choose font face and size for individual report objects. You are not limited to standard letter-oriented fonts—you may choose symbol fonts such as Wingdings and Webdings as easily as you can choose letter-oriented fonts.

 

1. Add a database field, text object, formula, or other textual element that you wish to display as a symbol to the report.

2. Ensure that the object returns a character value that will “map” to the proper symbol. For example, to display a smile or frown with theWingdings font, you might create a formula similar to this:

If {Customer.Last Year’s Sales} < 50000 Then

“L”

Else

“J”

3. Select the object you wish to format with a symbol font.

4. Either using the Formatting toolbar or the Format Editor, select the symbol font (such as Wingdings or Webdings) that you’d like to use.

Tip: To determine what the proper character value is for the desired symbol, make use of the Windows Character Map. You may choose the symbol font and character you’d like to use and copy the character to the clipboard. Then, when you paste the character into a Crystal Reports formula or text object, the proper symbol will appear when you format the object with the symbol font. The Character Map is available from the System Tools submenu of the Accessories menu from the Start button Programs list.

 

 

Eliminate Blank Address Lines

Crystal Reports is often used for form letters, envelopes, or other mailing applications. In many cases, there is a need to eliminate blank address or “suite number” lines in an address for certain addresses. This can be accomplished in two ways: by embedding multiple address lines in a text object, or by using multiple report sections.

The text object method, while simpler in approach, will not automatically adjust vertical placement of objects that follow on the report. For example, if the address contains four lines in one form letter and three lines in the next, the remainder of the form letter below the text object will not move up or down automatically depending on the vertical size of the text object. For situations that require automatic vertical adjustment of text that follows the address, you’ll need to use multiple report sections.

 

Text Object

To eliminate blank lines using a text object, follow these steps:

1. Add a text object to your report. You will combine several database fields inside this text object.

2. Display the Field Explorer. Drag desired fields into the text object, separating database field with necessary characters, such as commas and spaces. In particular, drag the first address line (that might contain the street number) into the text object. Press ENTER to add a carriage return. Then, drag the second address line that will not always contain data (this might contain the suite number) into the text object. Press ENTER again. Then, drag in City, State, and Zip Code.

3. End editing by clicking anywhere outside the text object.

4. Select the text object you just created. Right-click and choose Format Text from the pop-up menu. The Format Editor will appear.

5. On the Common tab, click the Suppress Embedded Field Blank Lines options. This will suppress any lines in the text object that contain no data.

 

Shade Every Other Report Line

Although most companies have replaced mainframe “green-bar” or “blue-bar” reports with laser-printed output, there’s still a benefit to shaded sections when heavy textual information is being viewed. Shading lines in alternate colors or shades makes it easier for the eye to follow the line across the page. Crystal Reports enables this technique to be easily used for reports that may be printed on paper or viewed online.

By using the Mod function (which performs modulus arithmetic—returning the remainder of a division operation instead of the quotient), combined with the RecordNumber function (which simply numbers each report record sequentially), you may produce creative banded reports.

 

1. Point to the gray Details section name in the Design tab, or the gray D section name in the Preview tab. Right-click.

2. Choose Format Section from the pop-up menu in Crystal Reports 8.5 or Section Expert from the pop-up menu in Crystal Reports 9. The Section Expert will appear.

3. Ensure that the Details section is selected in the Section Expert. Click the Color tab.

4. Click the Conditional Formatting button. The Format Formula Editor will appear.

5. Enter a formula similar to the following (you may change the formatting color to your desired color):

If RecordNumber Mod 2 = 0 Then crSilver Else crNoColor

6. You may alter the frequency of the banding if you desire. For example, to shade every two lines, you can modify the formula as follows:

If RecordNumber Mod 4 In 1 To 2 Then crSilver Else crNoColor

Tip: Use of the crNoColor color constant instead of crWhite will show the alternating report sections with a certain degree of transparency. This may be helpful for certain reporting situations where you wish background information (such as a watermark) to appear behind the sections.

Courtesy: The Seo Guru, A Software Development Company, Best OOPS Blog Site, Link Submission, Thanks to Shopping  Site for Link Exchanging

Code Sample to Upload file to FTP Server

Visit: https://zonixsoft.com

check out below code to upload file to FTP Server:

 

/// <summary>
/// Code to upload file to FTP Server
/// </summary>
/// <param name=”strFilePath”>Complete physical path of the file to be uploaded</param>
/// <param name=”strFTPPath”>FTP Path</param>
/// <param name=”strUserName”>FTP User account name</param>
/// <param name=”strPassword”>FTP User password</param>
/// <returns>Boolean value based on result</returns>
private bool UploadToFTP(string strFilePath, string strFTPPath, string strUserName, string strPassword)
{
        try
        { 
                //Create a FTP Request Object and Specfiy a Complete Path
                string strFileName = strFilePath.Substring(strFilePath.LastIndexOf(“\”) + 1);
                FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPPath + @”/” + strFileName);
                //Call A FileUpload Method of FTP Request Object
                reqObj.Method = WebRequestMethods.Ftp.UploadFile;
                //If you want to access Resourse Protected You need to give User Name and PWD
                reqObj.Credentials = new NetworkCredential(strUserName, strPassword);
                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(strFilePath);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                reqObj.ContentLength = fileContents.Length;
                Stream requestStream = reqObj.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
                response.Close();
        }
        catch (Exception Ex)
        {       // report error
                throw Ex;
        }
        return true;
}

Code Sample to Upload file to FTP Server

Visit: https://zonixsoft.com

check out below code to upload file to FTP Server:

 

/// <summary>
/// Code to upload file to FTP Server
/// </summary>
/// <param name=”strFilePath”>Complete physical path of the file to be uploaded</param>
/// <param name=”strFTPPath”>FTP Path</param>
/// <param name=”strUserName”>FTP User account name</param>
/// <param name=”strPassword”>FTP User password</param>
/// <returns>Boolean value based on result</returns>
private bool UploadToFTP(string strFilePath, string strFTPPath, string strUserName, string strPassword)
{
        try
        { 
                //Create a FTP Request Object and Specfiy a Complete Path
                string strFileName = strFilePath.Substring(strFilePath.LastIndexOf(“\”) + 1);
                FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPPath + @”/” + strFileName);
                //Call A FileUpload Method of FTP Request Object
                reqObj.Method = WebRequestMethods.Ftp.UploadFile;
                //If you want to access Resourse Protected You need to give User Name and PWD
                reqObj.Credentials = new NetworkCredential(strUserName, strPassword);
                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(strFilePath);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                reqObj.ContentLength = fileContents.Length;
                Stream requestStream = reqObj.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
                response.Close();
        }
        catch (Exception Ex)
        {       // report error
                throw Ex;
        }
        return true;
}

Icon in the Address bar Textbox in Browsers

Visit: https://zonixsoft.com

(Short Cut) Icon in the Address bar Textbox in Browsers

You have to insert this line after the <head> tag in your html / ASPX / Master Page.

<link rel=”shortcut icon” href=”images/MyComp.ico”>

Make sure the image is file type .ico (for icon). Also, after inserting this line, the image may not appear immediately. So, Try to Refresh the page.

Here’s an article for that:

How to Add a Shortcut Icon to a Web Page

 

Other way to achieve the same thing is as follows

 

       Save the icon with the default file name of favicon.ico to the root directory of your domain—for example, www.microsoft.com/favicon.ico. The first time a user visits your Web page, Internet Explorer automatically searches for this file and places the icon in the address bar, next to all favorites linking to your site, and on page tabs. In Internet Explorer 5 and Internet Explorer 6, the icon will appears only after a user adds the site to the Favorites menu.

 

You can use either method, or both. However, if you use the First method, whichever icon you point to in the link tag on each page will be displayed instead of the default favicon.ico file at the root of your domain.


Bookmark and Share

Convert Date Formats :

 

//For ex., Convert MM/dd/YYYY to dd/MM/yyyy

string date = “03/27/2008”; //format is MM/dd/yyyy

DateTimeFormatInfo dateTimeFormatterProvider = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;

dateTimeFormatterProvider.ShortDatePattern = “MM/dd/yyyy”; //source date format

DateTime dateTime = DateTime.Parse(date, dateTimeFormatterProvider);

string formatted = dateTime.ToString(“dd/MM/yyyy”); //write the format in which you want the date tobe converted

Response.Write(“<br />” + formatted);


Bookmark and Share

Convert Date Formats :

 

//For ex., Convert MM/dd/YYYY to dd/MM/yyyy

string date = “03/27/2008”; //format is MM/dd/yyyy

DateTimeFormatInfo dateTimeFormatterProvider = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;

dateTimeFormatterProvider.ShortDatePattern = “MM/dd/yyyy”; //source date format

DateTime dateTime = DateTime.Parse(date, dateTimeFormatterProvider);

string formatted = dateTime.ToString(“dd/MM/yyyy”); //write the format in which you want the date tobe converted

Response.Write(“<br />” + formatted);


Bookmark and Share

Customizing the Map using Google Maps API

Get ready to code! In this section, we’ll be making changes and additions to the map HTML file to customize the map based on your preferences.

 

1.    Open your myapp.html file.

2.    Add the code to center the map at particular the latitude/longitude .The line that centers the map in the current code is: map.setCenter(new GLatLng(37.4419, -122.1419), 13);

 

This line calls setCenter on the map object, and passes in a GLatLng for the center, and a number for the zoom level. Change the two parameters of GLatLng to the latitude/longitude you want to locate, and if you’d like, change the zoom parameter. Zoom level 0 is the lowest zoom level (showing all of the world), and increasing numbers zoom in closer.

 

3.    Add code to change the default map type. Currently the map is showing the Map map type, which shows street names, country borders, etc. The other two options are the Satellite and Hybrid map types. You can see the difference at http://maps.google.com by pressing each of the three buttons in the top right corner. The line of code to change the map type is:

    map.setMapType(G_NORMAL_MAP);

    map.setMapType(G_SATELLITE_MAP);

    map.setMapType(G_HYBRID_MAP);

 

    The default that it’s already using is G_NORMAL_MAP, so if you      want to change it, use either G_SATELLITE_MAP or G_HYBRID_MAP. Add this line of code after the map.setCenter code.

 

4.    Add the code to create a marker at the center of the map, like the markers you see when you find businesses on Google Maps. The line of code to create a marker is:

var marker = new GMarker(new GlatLng(34.019968,-118.289988));

The line of code to add a marker to the map is:

map.addOverlay(marker);

 

5.    Add the code to open an info window (bubble) over the marker and add some information about the location.

The code to open an info window over a marker is:

 

 

var html=”<img src=’simplemap_logo.jpg'” +

“width=’128′ height=’41’/> <br/>” +

“USC GamePipe Lab<br/>” +

“3650 McClintock Ave, Los Angeles CA”;

marker.openInfoWindowHtml(html);

As you can see from my example, you can pass any HTML into the info window. You do need to be careful about quotation marks in the HTML, however. Here, I’ve used double quotation marks around the HTML, and single quotation marks around attributes in the HTML tags.

If you include an IMG tag in the HTML, you should define the width and height attributes of the image so that the info window is sized correctly to fit the image inside.

 

 

6.    Add the code to add controls to the map. On the maps.google.com map, you’ll notice multiple controls overlaid on the map that aid you in navigation and changing the map view. With the API, you can add any of these controls to your map, and you may want to do so to let people visiting your map view the area around your map. Here are the various controls options:

map.addControl(new GSmallMapControl());

map.addControl(new GLargeMapControl());

map.addControl(new GSmallZoomControl());

map.addControl(new GScaleControl());

map.addControl(new GMapTypeControl());

map.addControl(new GoverviewMapControl());

 

You should only add one of the zoom/pan controls: either GSmallMapControl, GLargeMapControl, or GSmallZoomControl, since they show up in the same location and accomplish similar things. You can add any or all of the other controls, as you so desire. These lines of code should be added anywhere under the map.setCenter line.

   7.Change the HTML to resize the map. The default map has dimension of  500×300 pixels. You may want your map to be larger or smaller than that. The map size is dependent on the size of the div that the map is initialized within, so you’ll need to change the dimensions of that div to your desired dimensions. Find the following line of code and replace the default width and height to whatever you want:

 

<div id=”map” style=”width: 500px; height: 300px”></div>

 

 

Courtesy: The Seo Guru, A Software Development Company, Best OOPS Blog Site, Link Submission, Thanks to Shopping  Site for Link Exchanging


Bookmark and Share

Maintaining Fck editor value during postbacks

Here is the code to maintain value of FckEditor value during postbacks,

 

Write in Page_Load event,

 

Page.ClientScript.RegisterOnSubmitStatement(

fckContentPage.GetType(),

“fckContentPage”,

“FCKeditorAPI.GetInstance(‘” + fckContentPage.ClientID + “‘).UpdateLinkedField();”);

 

Here fckContentPage is ID of FckEditor


Bookmark and Share

Boxing and UnBoxing

 

 

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o.

int i = 123;
object o = (object)i;  // boxing

The object o can then be unboxed and assigned to integer variable i

o = 123;
i = (int)o;  // unboxing

 

Performance

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed.This can take up to 20 times longer than an assignment.  To a lesser degree, the cast required for unboxing is also expensive computationally. When unboxing, the casting process can take 4 times as long as an assignment. For more information, see Performance.

 

 

 


Bookmark and Share