Rss Feed Like Us on facebook Google Plus
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

June 28, 2016

Why is null not allowed for DateTime in C#?

DateTime is a value-type (struct), where-as string is a reference-type (class etc). That is the key difference. 

A reference can always be null; a value can't (unless it uses Nullable<T> - i.e. DateTime?), although it can be zero'd (DateTime.MinValue), which is often interpreted as the same thing as null 


C# that causes null DateTime error

using System;

class Program
{
    static void Main()
    {
 DateTime current = null;
    }
}

Results

error CS0037: Cannot convert null to 'DateTime'
because it is a non-nullable value type

Read More

June 16, 2014

Remove HTML Tags from a String of HTML using C#

When a String contains HTML tags (may be using CKEditor) and want to display HTML string as Plain Text. You can achieve by using Regular Expression..

string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();
string noHTMLNormalised = Regex.Replace(noHTML, @"\s{2,}", " ");

Note : A Regex cannot handle all HTML documents. An iterative solution, with a for-loop, may be best in many cases: always test methods.

Alternative

    public static class HtmlRemoval
    {
        /// <summary>
        /// Remove HTML from string with Regex.
        /// </summary>
        public static string StripTagsRegex(string source)
        {
            return Regex.Replace(source, "<.*?>", string.Empty);
        }
 
        /// <summary>
        /// Compiled regular expression for performance.
        /// </summary>
        static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
 
        /// <summary>
        /// Remove HTML from string with compiled Regex.
        /// </summary>
        public static string StripTagsRegexCompiled(string source)
        {
            return _htmlRegex.Replace(source, string.Empty);
        }
 
        /// <summary>
        /// Remove HTML tags from string using char array.
        /// </summary>
        public static string StripTagsCharArray(string source)
        {
            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;
 
            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }
    }
Read More

October 28, 2013

Dynamic Google Chart with Asp.net , C Sharp

To display live data on your site using Google chart with asp.net and C#.

  • Google chart tools are powerful, simple to use, and free. Try out our rich gallery of interactive charts and data tools
to create Dynamic Google chart with asp.net, we have to fetch data in Data Table with your preferred back-end server, checkout following steps...
  1. Fetch data in Data Table..
  2. Convert Data into JSON format
  3. Pass JSON Data to Script with web method
  4. Pass JSON Data to google.visualization.DataTable()
  5. Execute Google Chart Script - new google.visualization.ColumnChart("HtmlElementID")
Below is Code Example with three types of chart..(Column Chart, Line Chart, Combo Chart)

1. SCRIPT ( Design Page chart.aspx)

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Chart.aspx/GetData',  // Your aspx page url with web method..
                data: '{}',
                success:
                    function (response) {
                        drawVisualization(response.d);
                    }
            });
        })

        function drawVisualization(dataValues) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Product Catalogue');
            data.addColumn('number', 'Total Sales');
            data.addColumn('number', 'MOP');
            for (var i = 0; i < dataValues.length; i++) {
                data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Value2]);
            }
            var options = {
                title: 'Total Sales by Years',
                is3D: true,
                hAxis: { title: 'Product Catalogue', titleTextStyle: { color: 'red'} }
            };
            new google.visualization.ColumnChart(document.getElementById('Div1')).
                draw(data, options);

            new google.visualization.LineChart(document.getElementById('Div2')).
            draw(data, options);

            new google.visualization.ComboChart(document.getElementById('visualization')).
            draw(data, {
                title: 'Total Sales by Years',
                width: 600,
                height: 400,
                is3D: true,
                vAxis: { title: "Total Sales" },
                hAxis: { title: "Produt Catalogue" },
                seriesType: "bars",
                series: { 1: { type: "line"} }
            });
        }        
    </script>


2. HTML ( Design Page chart.aspx)

<body>
    <form id="form1" runat="server">
    <div>
        <div id="visualization" style="width: 600px; height: 350px;">
        </div>
        <div id="Div1" style="width: 600px; height: 350px;">
        </div>
        <div id="Div2" style="width: 600px; height: 350px;">
        </div>
    </div>
    </form>
</body>

3. Code Behind ( chart.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

public partial class Chart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static List<Data> GetData()
    {
        SqlConnection conn = new SqlConnection("--YOUR CONNECTION STRING--;");
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        conn.Open();
        string cmdstr = @"select productcatalogue,convert(decimal,sum(localamt)) as totalsales ,convert(decimal,sum(mop)) as mop
                        from [salesdata] group by productcatalogue ";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        dt = ds.Tables[0];
        List<Data> dataList = new List<Data>();
        string cat = "";
        decimal val = 0;
        decimal val2 = 0;
        foreach (DataRow dr in dt.Rows)
        {
            cat = dr[0].ToString();
            val = Convert.ToDecimal(dr[1]);
            val2 = Convert.ToDecimal(dr[2]);
            dataList.Add(new Data(cat,val,val2));
        }
        return dataList;
    }
}
public class Data
{
    public string ColumnName = "";
    public decimal Value = 0;
    public decimal Value2 = 0;
    public Data(string columnName, decimal value, decimal value2)
    {
        ColumnName = columnName;
        Value = value;
        Value2 = value2;
    }
}


Read More

September 11, 2013

Upload files to FTP server using C#

Upload any type of files (text,zip,images etc.) to FTP using C#


In order to upload a file using FTP details, one should know the server’s FTP URL, FTP username and FTP password.

We can achieve the file uploading task by using the below three inbuilt classes of .NET: FtpWebRequest,WebRequestMethods, and NetworkCredential.

Here is a sample code to upload TEXT file.

using System;
using System.IO;
using System.Net;
using System.Text;
 
namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;
 
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("testfile.txt");
            byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
 
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
 
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    
            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
    
            response.Close();
            }
        }
    }
}

>> As we know streamreader used only to read text files / binary files. here is sample code to upload all type of files.

private static void up(string sourceFile, string targetFile)
{            
    try
    {
        string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
        string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
        string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
        ////string ftpURI = "";
        string filename = "ftp://" + ftpServerIP + "//" + targetFile; 
        FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
        ftpReq.UseBinary = true;
        ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
        ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 
        byte[] b = File.ReadAllBytes(sourceFile);
 
        ftpReq.ContentLength = b.Length;
        using (Stream s = ftpReq.GetRequestStream())
        {
            s.Write(b, 0, b.Length);
        }
 
        FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
 
        if (ftpResp != null)
        {
            MessageBox.Show(ftpResp.StatusDescription);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}



Read More

July 21, 2013

How to optimize a Stored Procedure - SQL Server

We will go over how to optimize Stored Procedure with making simple changes in the code.
  • Include SET NOCOUNT ON statement: With every SELECT and DML statement, the SQL server returns a message that indicates the number of affected rows by that statement. This information is mostly helpful in debugging the code, but it is useless after that. By setting SET NOCOUNT ON, we can disable the feature of returning this extra information. For stored procedures that contain several statements or contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost because network traffic is greatly reduced.

CREATE PROC dbo.ProcName
AS
SET
NOCOUNT ON;
--Procedure code here
SELECT column1 FROM dbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO

  • Use schema name with object name: The object name is qualified if used with schema name. Schema name should be used with the stored procedure name and with all objects referenced inside the stored procedure. This help in directly finding the complied plan instead of searching the objects in other possible schema before finally deciding to use a cached plan, if available. This process of searching and deciding a schema for an object leads to COMPILE lock on stored procedure and decreases the stored procedure’s performance. Therefore, always refer the objects with qualified name in the stored procedure like

SELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method

  • Do not use the prefix “sp_” in the stored procedure name: If a stored procedure name begins with “SP_,” then SQL server first searches in the master database and then in the current session database. Searching in the master database causes extra overhead and even a wrong result if another stored procedure with the same name is found in master database.

  • Use IF EXISTS (SELECT 1) instead of (SELECT *): To check the existence of a record in another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any value is returned from an internal statement, either a single value “1” or all columns of a record or complete recordset. The output of the internal statement is not used. Hence, to minimize the data for processing and network transferring, we should use “1” in the SELECT clause of an internal statement, as shown below:

IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type = 'U')

  • Use the sp_executesql stored procedure instead of the EXECUTE statement.
    The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve the re-usability of your code. The execution plan of a dynamic statement can be reused only if each and every character, including case, space, comments and parameter, is same for two statements. For example, if we execute the below batch:

DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET
@Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' + CONVERT(VARCHAR(3),@Age)
EXEC (@Query)

If we again execute the above batch using different @Age value, then the execution plan for SELECT statement created for @Age =25 would not be reused. However, if we write the above batch as given below,

DECLARE @Query NVARCHAR(100)
SET @Query = N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25

the compiled plan of this SELECT statement will be reused for different value of @Age parameter. The reuse of the existing complied plan will result in improved performance.

  • Try to avoid using SQL Server cursors whenever possible: Cursor uses a lot of resources for overhead processing to maintain current record position in a recordset and this decreases the performance. If we need to process records one-by-one in a loop, then we should use the WHILE clause. Wherever possible, we should replace the cursor-based approach with SET-based approach. Because the SQL Server engine is designed and optimized to perform SET-based operation very fast. Again, please note cursor is also a kind of WHILE Loop.
  • Keep the Transaction as short as possible: The length of transaction affects blocking and deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation level, the shared locks are also aged with transaction. Therefore, lengthy transaction means locks for longer time and locks for longer time turns into blocking. In some cases, blocking also converts into deadlocks. So, for faster execution and less blocking, the transaction should be kept as short as possible.
  • Try to Avoid Inner Query (sub Query) - do not use inner queries in your stored procedure it slows down your sp.
  • Use Table Indexes - Tables should have proper indexes and should be compiled time to time as indexes may be weird off after some time due to huge data insertion or deletion.
  • Use TRY-Catch for error handling: Prior to SQL server 2005 version code for error handling, there was a big portion of actual code because an error check statement was written after every t-sql statement. More code always consumes more resources and time. In SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as follows:

BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH

Read More

July 12, 2013

Convert Web Page (Aspx,Html) to PDF File - Asp.net

For many developers while developing applications the question arises that How to Convert  Web Page (Aspx,Html,php) to PDF File. Solution is here..

You can convert any web URL in to PDF file by this utility.

Convert html to pdf using webkit (qtwebkit)

Searching the web, I have found several command line tools that allow you to convert a HTML-document to a PDF-document, however they all seem to use their own, and rather incomplete rendering engine, resulting in poor quality. Recently QT 4.4 was released with a WebKit widget (WebKit is the engine of Apples Safari, which is a fork of the KDE KHtml), and making a good tool became very easy.

Simple shell utility to convert HTML to PDF using the webkit rendering engine, and qt.

That is it. You can go to any web page... even aspx. is supported better than any other utility as it uses the web-kit HTML rendering engine (Safari, Chrome). Enjoy
There is a single .exe (7 mb) that can be used from .Net simply by using Process.Start Make sure that you copy the exe into your project directory or you have to specify the full path..

Example: -

public void HtmlToPdf(string website, string destinationFile)
    {
        try
        {
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\wkhtmltopdf.exe";
            website = "\"" + website + "\"";
            string arguments1 = website + " " + destinationFile;
            p.StartInfo.Arguments = arguments1;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.WaitForExit();
            p.Close();
            p.Dispose();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  
Read More

July 9, 2013

Real World Example of Abstract Class and Interface

An abstract class is a class that you cannot create an instance of. It can provide basic functionality, but in order for that functionality to be used, one or more other classes must derive from the abstract class. One of the major benefits of abstract classes is that you can reuse code without having to retype it. 

That has a plethora of benefits, such as reducing bugs and making coding faster. A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). 

The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

Now, an interface is like an abstract class, except it does not contain any logic. Rather, it specifies an interface. So, there might be an interface called IFly. This might have the methods GoForward and GoDown. Those methods would not actually contain any logic... each class that implements interface IFly would have to implement those GoForward and GoDown methods. You could have classes Duck and Finch implement interface IFly. Then, if you want to keep a list of instances that can fly, you just create a list that contains items of type IFly. That way, you can add Ducks and Finches and any other instance of a class the implements IFly to the list.

So, abstract classes can be used to consolidate and share functionality, while interfaces can be used to specify what the common functionality that will be shared between different instances will be, without actually building that functionality for them. Both can help you make your code smaller, just in different ways. There are other differences between interfaces and abstract classes, but those depend on the programming language, so I won't go into those other differences here.

Do you mean real-world as in "A live software system which includes  Abstract classes or interfaces" or do you mean "


If you mean the latter think of Vehicle as an abstract class. You can't yet do anything with it because you have no idea what it does, or how to drive it.

abstract class Vehicle{}

Vehicles could be split into morotized and pedal-powered, but still this is abstract, we still dont know what to do with it.

abstract class MotorVehicle : Vehicle {} 
abstract class PedaledVehicle : Vehicle {}

You could now define a concrete (non-abstract) class, like car.

class MotorCar : MotorVehicle {}

 Intefaces come in handy you can only inherit from one base class. So imagine some vehicles are drivable, others are remote controlled, some vehicles use a stearing wheel, others dont

interface IDrivable{}
interface IHasStearingWheel{}

Now you could derive a DrivableMotorCar from its base clas, and also implement other behaviours.
class DrivableMotorCar : MotorVehicle, IDrivable, IHasStearingWheel {}


Recommendations for Abstract Classes vs. Interfaces

The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Reference:-


Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.