Wednesday, December 15, 2010

Code Example for abstract and interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication3
{
   abstract class test
    {
        abstract public void print();
        public int y; //can initialise fields 
    }

     class Program:test

    {
         //abstract class
        public override void print()
        {
            x = 10;
            Console.WriteLine("Abstract  : test value :"+y.ToString());
        }
         //end of abstract
        public int x;
     }
     interface test_interface
     {
        void test();
         // int x; it gives the error as Error    "Interfaces cannot contain fields"            
     }
     class tt:Program,test_interface //inherit base class and interface
    {
        //interface
        public  void test()
        {
           
            Console.WriteLine("interface value");
        }
        //end
     }

   
    class main_class
    {
        static void Main(string[] args)
        {
           
            Program pp = new Program();//create instance for base class for abstract only;
            tt te=new tt(); //for both abstract and derived class
            te.print();//abstract
            te.test();//interface

            pp.print();//
           
            pp.x = 100;
            Console.WriteLine(pp.x);
            test_interface ttt = (test_interface)te;//type casting into interface type
            ttt.test();
        }
    }
}

Wednesday, November 24, 2010

code for creating sql server table as a xml file

DataTable data_table = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from test_table", connection);
da.Fill(ds);
ds.WriteXml(@"c:\output2.xml", XmlWriteMode.IgnoreSchema);
connection.Close();


Read XML file data

XmlTextReader xml_reader = new XmlTextReader(@"c:\output1.xml");
        XmlDocument xml_doc = new XmlDocument();
        xml_doc.Load(xml_reader);
        XmlNode select_node = xml_doc.SelectSingleNode("NewDataSet");
        node_list = xml_doc.GetElementsByTagName("Table");

        for (i = 0; i < node_list.Count; i++)
        {
            for (j = 0; j < node_list[i].ChildNodes.Count; j++)
            {
                     Response.Write(node_list[i].ChildNodes[j].InnerText);
            }
}

code for zip and unzip the file using c#

using System.IO.Compression;
using System.IO;


Zip the File

 FileStream sourceFile = File.OpenRead(@"C:\output1.xml");
        FileStream destFile = File.Create(@"C:\sample.zip");

        GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

        try
        {
            int theByte = sourceFile.ReadByte();
            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }
        }
        finally
        {
            compStream.Dispose();
        }


UnZip the File

 string srcFile = @"C:\sample.zip";
        string dstFile = @"C:\file_xml1.xml";

        FileStream file_stream_in = null;
        FileStream file_stream_out = null;
        GZipStream zip = null;
        const int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];
        int count = 0;

        try
        {

            file_stream_in  = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            file_stream_out  = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
            zip = new GZipStream(file_stream_in , CompressionMode.Decompress, true);
            while (true)
            {
                count = zip.Read(buffer, 0, bufferSize);
                if (count != 0)
                {
                    file_stream_out.Write(buffer, 0, count);
                }
                if (count != bufferSize)
                {
                 
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        
            System.Diagnostics.Debug.Assert(false, ex.ToString());
        }

Friday, October 15, 2010

code for using Jquery in asp.net

 protected override void Render(HtmlTextWriter writer)
    {
        this.Page.ClientScript.RegisterClientScriptInclude("jQuery", "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
        this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "startup", "");
        base.Render(writer);
    }

Jquery

       function test_alert()     {     $("#sample").animate({width: "70%",opacity: "0.4",marginLeft: "0.6in",fontSize: "3em",      borderWidth: "10px"}, 1500 );     //alert('Proceed to hide the message');     $("#sample").hide(3000,function () {     $(this).show(5000, function () {     $(this).slideUp(10000,function() {     $(this).slideDown(1000);        });     });     });     });     }     function helloWorld()     {         $("#sample").append("Hello World!!");          $("#sample").click(test_alert);          $("#sample").removeClass("bgcolor").addClass("newcolor");          $("#p:first").fadeTo("slow",0.33);             }                

Thursday, September 30, 2010

copying text file values as a database column values

Step 1   :   create a table name as login...

Step 2   :

BULK INSERT login FROM 'c:\test_sql.txt' WITH
(
FIELDTERMINATOR = ',',--Data format in text file is username,password in a row.it is used to trminate the symbol comma and assume as a 2 column values

ROWTERMINATOR = '\n' )    --for next line
GO

--Showing the Result
SELECT *
FROM login
GO

Wednesday, September 22, 2010

Stored procedure for finding number days in month

Finding number of days in a month

alter procedure no_of_days as
Declare @no_of_days int
Declare @prev_month varchar(100)
Declare @current_month varchar(100)
Declare @file_duration varchar(100)
DECLARE @returnDate INT
declare @days int

SET @returnDate = CASE WHEN MONTH(getdate())
IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(getdate()) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(getdate()) % 4 = 0
AND
YEAR(getdate()) % 100 != 0)
OR
(YEAR(getdate()) % 400 = 0)
THEN 29
ELSE 28 END
END

Get previous month name and current month name

set @no_of_days=@returnDate
set @prev_month=(Select Datename(mm, GetDate()-@no_of_days))
set @current_month=(Select Datename(mm, GetDate()))
set @file_duration=@prev_month+'-'+@current_month

Monday, September 13, 2010

Code for Copying Sql Table data into Excel file

Step 1:

Before run this procedure u have to create a excel template file with the relevant column name of the table.

Step 2:

Create PROCEDURE SP_Sql_Excel @File_Name as varchar(50) = ''
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @Dos_Command varchar(1000)
    DECLARE @reportname varchar(500)
    DECLARE @Oledb_provider varchar(100)
    DECLARE @Excel_String varchar(100)

--    New File Name to be created
    IF @File_Name = ''
        Select @reportname = 'C:\temp\Excel\Template1.xls'
    ELSE
        Select @reportname = 'C:\temp\Excel\' + @File_Name + '.xls'

--    FileCopy command string formation
    SELECT @Dos_Command = 'Copy C:\temp\Excel\Template1.xls ' + @reportname

--    Execute Dos Copy command
    EXEC MASTER..XP_CMDSHELL @Dos_Command, NO_OUTPUT

--    Mentioning the OLEDB povider and excel destination filename
    set @Oledb_provider = 'Microsoft.Jet.OLEDB.4.0'
    set @Excel_String = 'Excel 8.0;Database=' + @reportname

--    Executing the OPENROWSET Command for copying the sql data  contents to Excel sheet.
exec('insert into OPENrowset (''' + @Oledb_provider + ''',''' + @Excel_String + ''',''SELECT username,password FROM [Sheet1$]'') select username,password from login')

SET NOCOUNT OFF
END



Step 3:

Run the Procedure


Exec SP_Sql_Excel 'filename'

Tuesday, August 3, 2010

Connecting Remote computer via code

private connection_status;
 private IPAddress ip_address;
    private TcpClient tcp_server;


ip_address = IPAddress.Parse (TextBox1.Text);
        tcp_server = new TcpClient();
        tcp_server.Connect(ip_address, port number);
        connection_status = true;
        if (connection_status)
        {
            Response.Write("connected");
        }
        else
        {
            Response.Write ("Not connected");
        }

Thursday, June 17, 2010

Code for Download a file from a folder

string[] filepath = Directory.GetFiles(Server.MapPath("~\\upload files"));
            foreach (string fileName in filepath)
            {
                string filename_read = Path.GetFileNameWithoutExtension(fileName);
                if (hidden_tar_file.Value == filename_read)
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(fileName);
                    if (file.Exists)
                    {
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.WriteFile(file.FullName);
                        Response.End();
                    }
                }
         
            }

Tuesday, May 11, 2010

coding for connectoin remote desktop using c#

Process process_conectoin = new Process();
string exe = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
if (exe != null)
{
process_conectoin.StartInfo.FileName = exe;
process_conectoin.StartInfo.Arguments = "/v " + "192.168.1.2"; // ip or name of computer to connect
process_conectoin.Start();
}

 This is another way to run Remote desktop using c#.net

Steps for creating .RDP File for running remote connection from ur code.

step 1: Enter machine name,user name,password,domain name and check save password then click saveas button to save the RDP file in ur root folder.




 Step 2:the write the code given below.

  using System.Diagnostics;

        Process.Start(Server.MapPath("Filename.rdp"));

Monday, April 26, 2010

Adding css effect to gridview while you mouse over and out from gridview

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.className='PostingPanelTableGrids';"
e.Row.Attributes["onmouseout"] = "this.className='PostingPanelTableGrid';";
}

Thursday, April 1, 2010

Coding for checking status of ip with ping statment in asp.net with c#

string server_ip = "127.0.0.1";//address to verify, like 127.0.0.1
Ping _objPing = new Ping();
PingReply reply_ping;
reply_ping = p.Send(server_ip);
int ping_success = 0, ping_insuccess = 0;
for (int i = 0; i < 25; i++)
{
reply_ping = _objPing.Send(server_ip);
if (reply_ping.Address.ToString() == server_ip)
ping_success++;
else
ping_insuccess++;
Console.WriteLine("Pack. sent");
}
Console.WriteLine("sent = 4, recived = {0}, lost = {1}", ping_success, ping_insuccess);
Console.ReadKey();

Wednesday, March 31, 2010

Coding for show child gridview in gridview row

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Button b1 = (Button)row.FindControl("Button1");
GridView g1 = (GridView)row.FindControl("GridView2");
if (b1.Text == "Show")
{
g1.Visible = true;
b1.Text = "hide";
}
else if (b1.Text == "hide")
{
g1.Visible = false;
b1.Text = "show";
}
}

Friday, February 19, 2010

upload and download file from sqlserver

Creating sqlserver table

create table (id int,content_type varcahr(50),filename varcahr(50),filecontent varbinary(8000))


Code for c#.net



using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Data.SqlClient;
using System.IO;

public partial class filestore : System.Web.UI.Page
{
SqlConnection ObjSQlConnectionString = new SqlConnection("Data source=server_name;Initial Catalog=table_name;User Id=userid;Pwd=password");

protected void btn_upload_file_Click(object sender, EventArgs e)
{


string upload_path_name = upload.PostedFile.FileName.ToString();
string upload_file_name = Path.GetFileName(upload_path_name);
FileStream Upload_filestream = new FileStream(upload_path_name, FileMode.Open, FileAccess.Read);
BinaryReader upload_binaryreader = new BinaryReader(Upload_filestream);
Byte[] byte_data = upload_binaryreader.ReadBytes ((Int32)Upload_filestream.Length);
upload_binaryreader.Close();
Upload_filestream.Close();

if (upload.PostedFile.ContentType == "application/vnd.ms-excel")
{
//upload file in a seperate folder
upload.SaveAs("C:\\Inetpub\\wwwroot\\tools_test\\excel files\\"+upload_file_name);
}

Response.Write(byte_data.Length);


//insert data in sqlserver table

string insert_query = "insert into filestroage(content_type,filename,filecontent)values(@content_type,@filename,@filecontent)";

SqlCommand sql_command = new SqlCommand(insert_query, ObjSQlConnectionString);

sql_command.CommandType = CommandType.Text;

sql_command.Parameters.Add("@content_type", SqlDbType.VarChar).Value = upload.PostedFile.ContentType.ToString();
sql_command.Parameters.Add("@filename", SqlDbType.VarChar).Value = upload_file_name;
sql_command.Parameters.Add("@filecontent", SqlDbType.Binary).Value = byte_data;

ObjSQlConnectionString.Open();

sql_command.ExecuteNonQuery();

ObjSQlConnectionString.Close();

}

//Read files data from table
protected void Button1_Click(object sender, EventArgs e)
{
string strQuery = "select content_type,filename,filecontent from filestroage where id=@id";

SqlCommand sql_command = new SqlCommand(strQuery);

sql_command.Parameters.Add("@id", SqlDbType.Int).Value = 2;

DataTable data_table_query = GetData_table(sql_command);

if (data_table_query != null)
{
file_download (data_table_query);
}
}



private DataTable GetData_table(SqlCommand sql_command)
{
DataTable data_table = new DataTable();

SqlDataAdapter sql_adapter = new SqlDataAdapter();

sql_command.CommandType = CommandType.Text;

sql_command.Connection = ObjSQlConnectionString;

try
{
ObjSQlConnectionString.Open();

sql_adapter.SelectCommand = sql_command;

sql_adapter.Fill(data_table );

return data_table;

}

catch
{

return null;

}

finally
{

ObjSQlConnectionString.Close();

sql_adapter.Dispose();

ObjSQlConnectionString.Dispose();

}

}

//Download read data in their own file format
private void file_download(DataTable data_table_rows)
{

Byte[] data_bytes = (Byte[])data_table_rows.Rows[0]["filecontent"];

Response.Buffer = true;

Response.Charset = "";

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = data_table_rows.Rows[0]["content_type"].ToString();

Response.AddHeader("content-disposition", "attachment;filename="+ data_table_rows .Rows[0]["filename"].ToString());

Response.BinaryWrite(data_bytes);

Response.Flush();

Response.End();
}
}

Tuesday, February 16, 2010

Playing with simple Interface Concept

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program:interface_first ,interface_second
{

public static void Main()
{
Console.WriteLine("INTERFACE TEST\n");

//call by class objects.
Program call_interface_first = new Program();
call_interface_first.method_for_interface("Invoke first interface method using object of first class");
call_interface_first.methos_for_second_interface("Invoke second interface method using object of first class\n");

second_calss call_interface_second = new second_calss();
call_interface_second.method_for_interface("Invoke first interface method using object of second class\n");



interface_first first_interface_call = call_interface_first;
first_interface_call.method_for_interface("Call the first interface using interface object with assing class objects");
interface_second second_interface_call = call_interface_first;
second_interface_call.methos_for_second_interface("Call the second interface using interface object with assing class objects\n");

//call by same interface objects.
interface_first call_using_interface_refference = new Program();
call_using_interface_refference.method_for_interface("call first interface using the same interface reference");
interface_first call_using_interface_refference1 = new second_calss();
call_using_interface_refference1.method_for_interface("call second interface using the same interface reference\n");

//call by interface array with same reference.
interface_first[] array_interface = { new Program(), new second_calss() };
for (int i = 0; i <= 1; i++)
{
array_interface[i].method_for_interface("Invoke interface methods from class in array format :" + i);

}

}

public string method_for_interface(string i)
{

Console.WriteLine(i.ToString());
return i;
}
public string methos_for_second_interface(string s)
{
Console.WriteLine(s.ToString());
return s;
}

}

interface interface_first
{
//void interface_method_first();
string method_for_interface(string i);

}
interface interface_second
{
string methos_for_second_interface(string s);
}

//second class for accessing Interface
class second_calss : interface_first
{
public string method_for_interface(string s)
{
Console.WriteLine(s.ToString());
return s;
}
}
}

Friday, January 29, 2010

Code for sending sms from C# using way2sms api

Before Write a code use the steps given below

1. Add Web References to your page.
In that web references page just type this "http://www.spiritssoft.com/webservice/sendway2sms.asmx" in url optoin and click go

After Added that

2. use the name space Using com.spiritssoft.www

3. create a object for sending a sms
SendWay2Sms Objsms_send = new SendWay2Sms();

4.write the code given below here

Note: If you send to a single number just write the code what given here.If you want to send more than one person use comma(,) to seperate the numbers.


For sending one number:

String Strsms_result=Objsms_send.sendSmsSpiritsSoft("UserName", "Password", "Number", "message");

For sending more than numbers:

String Strsms_result=Objsms_send.sendSmsSpiritsSoft("UserName", "Password", "Number 1,Number 2,Number 3", "message");

Thursday, January 28, 2010

Coding for Accessing Sub Directory file with authentication mode as Forms using a web config file

IF u have a single Folder you should write the given code below

Code in a Web Config Root File

Note: when u use this code Just ignore to type Double quotes with the tags.

"<" configuration ">"
"<" location path="Your first sub directory folder Name" ">"
"<" system.web ">"
"<" authorization ">"
"<" allow users="*" "/>"
"<"/ authorization ">"
"<"/ system.web ">"
"<"/ location ">"
"<"/ configuration ">"

If you have more than one folder write the code given below

"<" configuration ">"

"<" location path="Your first sub directory folder Name" ">"
"<" system.web ">"
"<" authorization ">"
"<" allow users="*" "/>"
"<"/ authorization ">"
"<"/ system.web ">"
"<"/ location ">"

"<" location path="Your Secondary sub directory folder Name" ">"
"<" system.web ">"
"<" authorization ">"
"<" allow users="*" "/>"
"<"/ authorization ">"
"<"/ system.web ">"
"<"/ location ">"

"<"/ configuration ">"