December 26, 2010

Code Snippets in C# Useful for Beginners

1.)Below Is the Code Snippet To reverse The String


public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

2.)Add The numbers Entered in a TextBox as String
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_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:TextBox ID="txtInputArray" runat="server"></asp:TextBox><br />
         <asp:Button ID="btnSum" runat="server" Text="SUM" OnClick="btnSum_Click" />
        </div>
    </form>
</body>
</html>
Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

    }
    protected void btnSum_Click(object sender, EventArgs e)
    {
        int result=AddNumbers(txtInputArray.Text);

        Response.Write(result);
    }

    public int AddNumbers(string str)
    {
        char[] Arr = str.ToCharArray();
        int ArrayLen = Arr.Length;
        int result = 0;

        for (int i = 0; i < ArrayLen; i++)
        {

            result = result + int.Parse (Arr[i].ToString ());
        }

        return result;

    }
}


December 25, 2010

Replacing \n line breaks with HTML line breaks in Gridview

I was Inputting values from textArea and showing it in a gridview .
I realized whenever I m Pressing Enter I m not getting the line break in GridView.
because while Saving values in DB from TextArea ,was saving Line Break in newline Char (\n)
which is Non-HTMl Char and won't be read in GridView.
So Below is the solution I used for replacing it with HTML Break (<br/>).

protected void gridHistory_RowDataBound(object sender, GridViewRowEventArgs e)
{
 GridViewRow row = e.Row;
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  row.Cells[0].Text = row.Cells[0].Text.Replace("\n", "<br />");
 }
}

December 20, 2010

Static /Private constructor


Static Constructors
Static Constructor is defined with keyword  static , It gets called only for one time after class
has been loaded .

Uses of static constructors. 
1.)If the class is static it can not be instantiated, In that case to initialize the variables we can
    write the static constructor 




Below is the example of calling static constructor

public static class EXPStaticConstructor
{


static int i;
    // Static constructor:
    static EXPStaticConstructor()
    {
        i = 10;
        System.Console.WriteLine("Initialized i in Static Constructor");
    }

    static void someMethod()
    {

        System.Console.WriteLine("The Some method invoked.");
        System.Console.WriteLine(i);


    }
}
    private class Teststatic
    {
        static void Main()
        {


            EXPStaticConstructor.someMethod();  //Before calling this method the static constructor will be called as We are first time using the class EXPStaticConstructor
 for calling the method 
        }
    }





Private Constructors
Instance constructors are public. If we change the access level of an instance constructor to private or if we haven’t specified any access modifiers at all , it becomes a private constructor
Like methods, default access level of a constructor is private.
It is not possible to inherit a class that has only private constructors.
Uses of private constructors. 
**********************
1. Private constructors are commonly used in classes that contain only static 
members.This helps to prevent the creation of an instance of a class by other classes when there are no instance fields or methods in that class.
2. Private constructors are useful when you want to create an instance of a class within
a member of the same class and not want to instantiate it out side the class.
3. Private constructors are used to create an instance of a class within a member of a nested class of the same class.


Below IS the Example of Calling Private Constructor from the inner class
  class Program
    {
        static void Main(string[] args)
             {
                     outer.Inner i = new outer.Inner();
        }
    }
     class outer
    {
        private outer()
        {
            System.Console.WriteLine("Private");
        }


        public  class Inner
        {
            public Inner()
            {
                new outer();    //calling private constructor of outer class
            }


         


        }
    }




Below is the example for calling Private Constructor withing the method
public class EXPPrivate
{
    static int i;
    private EXPPrivate()
    {

        i = 10;
    }

    public static void Create()
    {
        EXPPrivate obj = new EXPPrivate();    // this creates an object  and calls the private constructor

    }

    static void Main()
    {


        Create();

        System.Console.WriteLine(i);

    }
}

October 21, 2010

GallaryServerPro SetUp From SourceCode

I downloaded GalleryServerPro_V2_3_3750_source from the below link
http://www.galleryserverpro.com/download.aspx

I am using sqlserver 2008/Visual studio 2008/.net Framework 3.5
Below are the steps I followed to make it work.

  1. Unzip GalleryServerPro_V2_3_3750_source.zip in physical directory.
  2. Open Visual Studio 2k8 
  3. Click On Open web site 
  4. Select folder GalleryServerPro_V2_3_3750_source\Website and Click Ok.
  5. From the solution explorer delete the SqlLite.dll from the bin folder
  6. Copy the content of web_sqlserver_3.5.config  into  web.config(as I am using the sqlserver and .netframework 3.5) 
  7. Open GalleryServerPro_V2_3_3750_source\Website\gs\config\galleryserverpro.config and change the Sqllite provider to SqlServer Provider by replacing 
                      <dataProvider defaultProvider="SQLiteGalleryServerProProvider">
                               to this:
                    <dataProvider defaultProvider="SqlServerGalleryServerProProvider">.

           To Install the database hit the below link
            http://localhost/Website/default.aspx?g=install
            Follow the wizard Steps and provide the DBserver Information , Database ll be installed 

           To visit the gallary hit the below link
           http://localhost/Website/default.aspx




October 10, 2010

Performance Counters not able to see in Windows xp


Yesterday I was trying to see my ASP.NET Application Performance but when i clicked on add objects to add the ASP.NET Application in performance counter , No Objects were there.It was a problem of corrupted relevant file.I followed below steps to make it work



1.       Start Regedit.exe. (You cannot use Regedt32.exe because it does not allow searching for registry values.)
2.       Click to select the following key
3.       HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
4.       Select Find from the Edit menu.
5.       In the Find What field, type Disable Performance Counters.
6.       Click Find Next. This will locate a Performance key that may have this Registry value set to 1.
7.       If the Registry value is set to 1, set the value to 0 or delete the Registry value.
8.       Press F3 to find the next occurrence of this Registry value.
9.       Repeat the previous two steps until there are no Performance keys that have theDisable Performance Counters value set to 1.
10.   copy C:\WINDOWS\system32\PerfStringBackup.INI from a PC where performance counter  works correctly
11.   cd C:\WINDOWS\system32
12.   lodctr /R:PerfStringBackup.INI





October 8, 2010

File Uploader on Godaddy Server C# Code

I wanted to upload a .pdf file from my web Application to my server which is shared server on Godaddy.
I thought to use the FTP Upload so below is the code which I used 



 //public void ftpfile(string ftpfilepath, string inputfilepath)
    //{
    //    string ftphost = "127.0.0.1";
    //    //here correct hostname or IP of the ftp server to be given  


    //    string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
    //    System.Net.FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
    //    ftp.Credentials = new NetworkCredential("username", "password");
    //    //userid and password for the ftp server to given  


    //    ftp.KeepAlive = true;
    //    ftp.UseBinary = true;
    //    ftp.Method = WebRequestMethods.Ftp.UploadFile;
    //    FileStream fs = File.OpenRead(inputfilepath);
    //    byte[] buffer = new byte[fs.Length];
    //    fs.Read(buffer, 0, buffer.Length);
    //    fs.Close();
    //    Stream ftpstream = ftp.GetRequestStream();
    //    ftpstream.Write(buffer, 0, buffer.Length);
    //    ftpstream.Close();
    //}

Above code worked well from my Local machine and I was able to transfer the file to the godaddy hosting server.but the same code when I deployed on server gave the following error

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. 

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +58
   System.Net.FtpWebRequest..ctor(Uri uri) +161
   System.Net.FtpWebRequestCreator.Create(Uri uri) +24
   System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) +216
   System.Net.WebRequest.Create(String requestUriString) +44
   Upload.ftpfile(String ftpfilepath, String inputfilepath) +32
   Upload.btnUpload_Click(Object sender, EventArgs e) +58
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242
   System.Web.UI.Page.ProcessRequest() +80
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +49
   ASP.upload_aspx.ProcessRequest(HttpContext context) +4
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3053

I tried to change the trust level in web.config file but Godaddy has blocked it you can not make the Hight Trust.
So I left that idea and used the File Uploader Control of ASP.NET 2.0 and below is the code which I wrote on Upload Click Button

 protected void btnUpload_Click(object sender, EventArgs e)
    {
 string filePath = "~/";
        string fileName = FileUpload1.FileName.ToString();
       FileUpload1.SaveAs(Server.MapPath(filePath) + "Test-brochure.pdf");
}


I uploaded the above code and it worked fine and the .pdf file was getting saved with the name Test-brochure.pdf in the root directory.but in this case my pdf file size was 26kb.

but when i gave the 25MB size file I/p .It din't work In Uploading progess bar it went till 15% then again came to 0 and went till 15% and the page has been removed from the server was coming.

I realized that the problem was of file size
so to make it work for the 25MB  file size I added the following node in <system.web> in web.config file

<httpRuntime 
executionTimeout="330" 
maxRequestLength="33792" 
requestLengthDiskThreshold="80" 
useFullyQualifiedRedirectUrl="false" 
minFreeThreads="8" 
minLocalRequestFreeThreads="4" 
appRequestQueueLimit="5000" 
enableKernelOutputCache="true" 
enableVersionHeader="true" 
requireRootedSaveAsPath="true" 
enable="true" 
shutdownTimeout="90" 
delayNotificationTimeout="5" 
waitChangeNotification="0" 
maxWaitChangeNotification="0" 
enableHeaderChecking="true" 
sendCacheControlHeader="true" 
apartmentThreading="false" />

basically these two highlighted attributes i increased according to my file size .
default is the below in machine.config
             <httpRuntime maxRequestLength="4096" />

and 
<httpRuntime maxRequestLength="10000" />
will establish a max file upload size of 10,000 Kilobytes.


You can change this attribute according to ur file size
You can set this more broadly in your machine.config, too.

September 30, 2010

SQL Server 2008

I was recently upgrading my NopCommerce version 1.4 to 1.8 , I had visual studio 2008 bit 1.8 runs on Visual Studio  2010 When I installed Visual web express 2010 SqlServer 2008 also got installed on my machine while I had SqlServer 2005. I wanted to continue with it . So I uninstalled sqlserver 2008.
but I was shocked to see that I was not able to connect to sqlserver 2005. My login was changed 
I uninstalled 2005 and reinstalled it Before that I took back up of my Database's files .
when I reinstalled SqlServer 2005 . I tried to attach the database but I was getting the following error.

The database '[path\MDF file] cannot be opened because it is version 655. This server supports version 611 and earlier. A downgrade path is not supported.
I searched and found that my databases are no longer compatible with SqlServer 2005, as when I installed VisualwebExpress 2010 sqlserver 2008 also got installed and it upgraded my databases too.
Now I have no option other then using sql server 2008.
I struggled with installation of sql server 2008 , As no clear direction found this on SQL Express home page:
 Here is what you can look for.
You can manually download and install any edition of SQL Server 2008 directly from the Microsoft Download Center:
SQL Server 2008  is available in the following 3 editions 
  • SQL Server 2008 Express




    • SQL Server database engine - create, store, update and retrieve your data
  • SQL Server 2008 Express with Tools




    • SQL Server database engine - create, store, update and retrieve your data
    • SQL Server Management Studio Basic - visual database management tool for creating, editing and managing databases
  • SQL Server 2008 Express with Advanced Services




    • SQL Server database engine - create, store, update and retrieve your data
    • SQL Server Management Studio Basic - visual database management tool for creating, editing and managing databases
    • Full-text Search - powerful, high-speed engine for searching text-intensive data
    • Reporting Services - integrated report creation and design environment to create reports
So make sure you download the SQL Server 2008 Express with Tools(It will install Managment Studio as a tool)
Here are the prerequisites for installing SqlServer 2008 Express with tools





Download and install  Microsoft .Net Framework 3.5 SP1.

Step 2 Download and install 
Windows Installer 4.5
 [important of you have pre-Vista OS].
.
Step 3 Download and install Windows PowerShell 1.0
And one more thing: If you have non-SP1 version of Visual Studio 2008, you will be stopped at the very last step before the install begins!!! So if you have VS2008 or any 2008 Express products, upgrade them to SP1 to install the Tools version to get your Management Studio Express.
http://www.microsoft.com/downloads/en/details.aspx?FamilyId=7522A683-4CB2-454E-B908-E805E9BD4E28&displaylang=en

 Uninstall the existing sql server and it's components

 Uninstall the "SQL Server 2008 Express" installation completely from your Windows Server.
 Reboot for sure.. but it's not necessary
 

 Install "Microsoft SQL Server 2008 Express with Tools" (SQLEXPRWT_x64_ENU.exe)

1. If you run "SQLEXPRWT_x86_ENU.exe", you'll come across a "SQL Server Installation Center" window.
2. You normally click at the "Installation" tab on the left pane, and click "New SQL Server stand-alone installation or add features to an existing installation".
3. A "SQL Server 2008 Setup" installation window appears, and have the following steps included:
- Setup Support Rules
- Installation Type
- Product Key (depending on the type of installation type you selected)
- and so on...
4. Once you get to the "Installation Type" step of the installation, instead of adding a new feature to the existing SQL Instance (that I initially setup as SQLExpress), try the install new instance, or something to that effect. There are only two options in this portion, so it won't be difficult to select.
5. Click next until you reach the "Feature Selection" step of the installation. There, select All
(If you ll only select management studio not the Database engine , Your installation will be done successfully but you ll not be able to connect to server as there will be no services installed and restarted)
6. Install on