Popular Posts

Sunday, 25 August 2013

How to Create a File or Folder IN ASP.NET

How to Create a File or Folder IN ASP.NET


Lets see how can we create Files and folder in out computer with the help of the asp.net.


YOU can create the file or folder and even subfolder in any directory of you pc.In this example I have made it possible to enter the path where you want to save the file and it creates the directory as well file.
If you Do Not provide the path then the file will be created at the path specifed(HARD CODED).


SO LETS SEE HOW TO DO IT...................................................................................................

THE CODE DESIGN PAGE:
<%@ 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>Create a File or Folder (C#)</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:Label ID="Label1" runat="server" Text="ENTER THE FILE NAME :"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
        ControlToValidate="TextBox1" Display="Dynamic" 
        ErrorMessage="ENTER ANY FILE NAME" Font-Bold="True" Font-Size="X-Small" 
        SetFocusOnError="True" ValidationGroup="File">THE FILE CREATED WILL BR IN TXT FORMAT</asp:RequiredFieldValidator><br />
    <br />
    <br />
    <asp:Label ID="Label2" runat="server" Text="STORAGE LOCATION :"></asp:Label>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
&nbsp;<h5>*NOT NECESSARY( IF PLEASE SPECIFY IN FORMAT MENTIONED:&nbsp; 
        DIRECTORY:/PARENT_FOLDERNAME/SUBFOLDERNAME)&nbsp; i.e d:/PARENT FOLDERNAME/SUB 
        FOLDERNAME&nbsp;&nbsp; OR d:/PARENT FOLDERNAME</h5><br />
    <br />
    <asp:Button ID="Button1" runat="server" Font-Bold="True" ForeColor="#33CC33" 
        Text="CREATE FILE" ValidationGroup="File" onclick="Button1_Click" />
    <br />
    <br />
    <asp:Label ID="resultlbl" runat="server" Font-Bold="True" Font-Size="Large" 
        ForeColor="#000066"></asp:Label>
    <asp:LinkButton ID="LinkButton1" runat="server" Visible="False">GO TO FILE</asp:LinkButton>
    </form>
</body>
</html>

YOU GET THE DESIGN:







THE CODE BEHIND:

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

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pathString = "";
        string pathString2 = "";
        // Create a file name for the file you want to create.  
        //string fileName = System.IO.Path.GetRandomFileName();

        // This example uses a random string for the name, but you also can specify 
        // a particular name. 
        string fileName = TextBox1.Text.ToUpper() + ".txt";

        if (TextBox2.Text.Equals(""))
        {
            // Specify a name for your PARENT_FOLDER folder. 
            string folderName = @"D:\MYPARENTFOLDER";

            // To create a string that specifies the path to a subfolder under your  
            // PARENT_FOLDER folder, add a name for the subfolder to folderName. 
            pathString = System.IO.Path.Combine(folderName, "MYSubFolder");

            // You can write out the path name directly instead of using the Combine 
            // method. Combine just makes the process easier. 
            pathString2 = @"c:\MyParentFolder\MYSubFolder";

            // You can extend the depth of your path if you want to. 
            //pathString = System.IO.Path.Combine(pathString, "SubSubFolder");

            // Create the subfolder. You can verify in File Explorer that you have this 
            // structure in the C: drive. 
            //    Local Disk (C:) 
            //        Top-Level Folder 
            //            SubFolder
            System.IO.Directory.CreateDirectory(pathString);


            // Use Combine again to add the file name to the path.
            pathString = System.IO.Path.Combine(pathString, fileName);

            // Verify the path that you have constructed.
            resultlbl.Text = "FILE CREATED AT Path " + pathString;

            // Check that the file doesn't already exist. If it doesn't exist, create 
            // the file and write integers 0 - 99 to it. 
            // DANGER: System.IO.File.Create will overwrite the file if it already exists. 
            // This could happen even with random file names, although it is unlikely. 
        

           

            
        }
        else
        {

            if (TextBox2.Text.Count(x => (x != '/')) > 0)
            {
                string FULLPATH = TextBox2.Text.ToString();


                pathString = FULLPATH;

            }
            else
            {
                string FULLPATH = TextBox2.Text.ToString();


                pathString =FULLPATH;

            }

            // You can extend the depth of your path if you want to. 
            //pathString = System.IO.Path.Combine(pathString, "SubSubFolder");

            // Create the subfolder. You can verify in File Explorer that you have this 
            // structure in the C: drive. 
            //    Local Disk (C:) 
            //        Top-Level Folder 
            //            SubFolder
            System.IO.Directory.CreateDirectory(pathString);


            // Use Combine again to add the file name to the path.
            pathString = System.IO.Path.Combine(pathString, fileName);

            // Verify the path that you have constructed.
            resultlbl.Text = "FILE CREATED AT Path " + pathString;
        }
        if (!System.IO.File.Exists(pathString))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(pathString))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }
        else
        {
            resultlbl.Text="File already exists with Filename"+ fileName+" At Location:"+pathString;

            LinkButton1.Visible = true;
            LinkButton1.PostBackUrl = pathString;
            Response.ContentType = @"application/txt";     //here we have selected TXT type file

            Response.AddHeader(
                @"Content-Disposition",
                @"attachment; filename=" + Path.GetFileName(pathString));


            Response.WriteFile(pathString);
            Response.End();
            return;
        }

        // Read and display the data from your file. 
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
            foreach (byte b in readBuffer)
            {
                Console.Write(b + " ");
            }
            Console.WriteLine();
        }
        catch (System.IO.IOException ex)
        {
            Console.WriteLine(ex.Message);
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        //System.Console.ReadKey();
    }
    

}



OUTPUT:






SO ITS DONE EASY ............................................

HENCE YOUR PROBLEM SOLVED..............................

So JUST COPY AND (!!!!UNDERSTAND.......) AND GET 

AMAZED ON YOUR INTELLIGENCE

IF ANY ERROR OR SUGGESTION IS ,ALWAYS 

WELCOME....................................................................
THANKS FOR BEARING..........................................................................................

DOWNLOADABLE PATH FROM OTHER DIRECTORY THAN APPLICATION DIRECTORY

CREATE FILE DIRECTORY AT PATH OTHER THAN YOUR APPLICATION PATH


Sometime when you host your application in specific director then you need to keep your downloadable folder that contains material that are needed to be download in other director rather than the hosting environment .
For Example :
you have hosted the application in C DRIVE OF YOUR SERVER.
BUT YOU WANT THE REPORTS DOWNLOAD FOLDER TO BE KEPT IN SOME OTHER DRIVE SAY D: AS IT SAVES THE SPACE OF C DRIVE AND MAKES MORE OF YOUR DATA SAFE AND APPLICATION FAST .

IF YOU GIVE THE LINK OF OTHER DIRECTOR AT DOWNLOAD BUTTON IT WILL GIVE ERROR AS:

The system cannot find the path specified OR


So lets see how to do it.........................................................................................................................


THE CODE DESIGN:create the scenario where ANY file need to be downloaded on button click.


THE CODE BEHIND:

protected void btnDownLoads_Click(object sender, EventArgs e)
    {
   
         string FolderName="WHERE YOUR FILES ARE KEPT"
      string SUBFolderName="SUB FOLDER NAME WHERE YOUR FILES ARE KEPT UNDER        FOLDERNAME";
     
        string filename ="your file need to be downloaded";
   
        string location =FolderName+ "/" + SUBFolderName + "/" + filename;

 

 var filePath = Path.Combine(@"ANOTHER DIRECTORY\PARENT FOLDER\SUBFOLDER\" + FolderName + " \" + SUBFolderName+ "", filename);

//its your choice to keep sub folder ,depending to the hierarchy..
// eg:  var filePath = Path.Combine(@"D:\Project\MainProject FOLDER\" + foldername + " ", filename);
     
Response.ContentType = @"application/pdf";     //here we have selected PDF type file

        Response.AddHeader(
            @"Content-Disposition",
            @"attachment; filename=" + Path.GetFileName(filePath));


        Response.WriteFile(filePath);
        Response.End();

     

............................................................................................................................................................

IT's DONE ...COOL NA.
SO ENJOY



ERROR WHILE RETRIVING COLUMNS FROM DATABASE(SELECT QUERY)

YES SOmetimes the simple looking retrival becomes so headache that you douth your capabilities.The simple retrival of the data from database WITH SELECT QUERY.


Lets see the simple example and look into the matteR:



SAY a TABLE is created with name seismic_details .It contains the information of the area and time where earth quack occurs.

desc seismic_details   //describe the database table
Name             Null Type          
---------------- ---- ------------- 
SI_NO                 NUMBER(5)     
DATES                 VARCHAR2(25)  
Time(IST)             VARCHAR2(25)  
EPICENTER_REGION      VARCHAR2(100) 
LAT(North)            FLOAT(126)    
LONG(East)            FLOAT(126)    
MAGNITUDE             FLOAT(126) 

NOW when you name the table name or the column name with special character in it i.e(contains (,)-@) etc then the name has to be retrieved via putting in DOUBLES QUOTES"".

i.e NOW your retrival query will becomes:
  SELECT SI_NO,
  DATES,
  "Time(IST)",
  EPICENTER_REGION,
 "LAT(North)",
  "LONG(East)",
  MAGNITUDE 
FROM SEISMIC_DETAILS ;



THE CODE BEHIND:

If you are not getting query result due to column names then fire like this:

 


 strSql = "select DATES," + '"' + "Time(IST)" + '"' + " ,EPICENTER_REGION,"+'"'+"LAT(North)"+'"'+","+'"'+"LONG(East)"+'"'+",MAGNITUDE FROM seismic_details "




Yes their are more and more ways....it depends on you...just chose the one that works for U.

SO ENJOY.........................................................

How to get html control in server side

How to get html control in server side

 

OK this is the most important issues that we get while programming ,,,when we want to use the html controls and also need to call them at server side .So check it out how we do it......


The design part:

<TABLE>
<tr style='color: #FF3300; text-decoration: underline'>
<td><input width='200px' id="HTMLTEXT1"  name="HTMLTEXT1" type='text' />
TEST HTML TEXT1
</td>
<td>
<input width='200px'  id="HTMLTEXT2" name="HTMLTEXT2" type='text' />
TEST HTML TEXT2
</td>
<td><input width='50px'  id="HTMLTEXT2" name='HTMLTEXT3" type='text' /> 
TEST HTML TEXT2
</td>
</tr>
</TABLE>;

 

Here we have taken three html text box and provided them with "ID" AND "NAME" attribute.
this NAME attribute will be used to take the value in the server side control. 

 


SERVER SIDE CODE BEHIND:

Now We will create three variables and store the values of the HTML text box using REQUEST OBJECT.

 string first_textvalue= this.Request.Form.Get("HTMLTEXT1");   
 string second_textvalue= this.Request.Form.Get("HTMLTEXT2");

 string third_textvalue= this.Request.Form.Get("HTMLTEXT3");





COOL ....that it...HENCE YOUR PROBLEM SOLVED ..............................So JUST COPY AND (!!!!UNDERSTAND.......) AND GET AMAZED ON YOUR INTELLIGENCEIF ANY ERROR OR SUGGESTION  IS ,ALWAYS WELCOME....................................................................THANKS FOR BEARING.............................................................................................................................. 

LETS HANDLE THE ERRRORS ORACLE TOP 10.......

LETS HANDLE THE ERRRORS ORACLE TOP 10.......

 Reference: Oracle Documentation 

1. Error Message: ORA-01839: date not valid for month specified

Cause of Error:You tried to enter a date value, but you specified an invalid day value.
Resolution:The option(s) to resolve this Oracle error are:
Option #1Check your DD value (ie: day of the month). This value must be between 1 and the number of days in the month.
·         January - 1 to 31
·         February - 1 to 28 (1 to 29, if a leap year)
·         March - 1 to 31
·         April - 1 to 30
·         May - 1 to 31
·         June - 1 to 30
·         July - 1 to 31
·         August - 1 to 31
·         September - 1 to 30
·         October - 1 to 31
·         November - 1 to 30
·        
December - 1 to 31


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2. Error Message: ORA-01722: invalid number

Cause of Error: 

The attempted conversion of a character string to a number failed because the character string was not a valid numeric literal. Only numeric fields or character fields containing numeric data may be used in arithmetic functions or expressions. Only numeric fields may be added to or subtracted from dates.



Resolution: 

Check the character strings in the function or expression. Check that they contain only numbers, a sign, a decimal point, and the character "E" or "e" and retry the operation




3. Error Message : ORA-12154:

TNS:couldnot resolve the connect identifier specified




Cause of Error:

A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.


Resolution:


- If you are using local naming (TNSNAMES.ORA file):- Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)- Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.- Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.- Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.- If you are using directory naming:- Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).- Verify that the LDAP directory server is up and that it is accessible.- Verify that the net service name or database name used as the connect identifier is configured in the directory.- Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier- If you are using easy connect naming:- Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).- Make sure the host, port and service name specified are correct.- Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.





4. Error Message: ORA-00600 internal error code

ORA-00600 internal error code, arguments: 
[string], [string], [string], [string], [string], [string], [string], [string]
 

Cause of Error:

:  This is the generic internal error number for Oracle program exceptions. 
This indicates that a process has encountered a low-level, unexpected condition.
Causes of this message include:
 - timeouts
 - file corruption
 - failed data checks in memory
 - hardware, memory, or I/O errors
 - incorrectly restored files
 
Resolution: 

Report as a bug - the first argument is the internal error number
 

Description of ORA-00600: A typical ORA-00600 error does not include descriptive text. The message text can
be followed by up to six arguments, which indicate the origin and attributes of the
error. The first argument is the internal error number. Other arguments are various
numbers, names, and character strings. The numbers may change meanings betweendifferent versions of Oracle. Empty brackets may be ignored. In addition to being returned to the user, internal errors are also written to theAlert file along with additional information about the event. The Alert file alsolists any trace files that may have been generated because of an internal error.
 If you receive an ORA-00600 message, report it to Oracle Support Services. Troubleshooting ORA-00600:Assume we encounter following ORA-00600 exceptionORA-00600: internal error code, arguments: [17069],[18798616],[],[],[] Metalink provides a very useful ORA-00600 Troubleshooter tool (Metalink Note:153788.1)to allow you to get the description for an ORA-00600  error.In this web tool, we can enter the 17069 (first argument) for the 17069 error: Login into the Metalink account and search for doc id “153788.1? in the
Quick find search bar and open the document.
 Follow following steps to lookup by code:a. Select the correct Error code ORA-00600b. Provide first argument of ORA-00600c. Select the appropriate database versiond. Click Lookup Error button

------------------------------------------------------------------------------------------------------------ 


5.  Error Message:ORA-12560:TNS PROTOCOL ADAPTER ERROR


Cause of Error:

 A generic protocol adapter error occurred.

Resolution:

Check addresses used for proper protocol specification. Before reporting this error, look at the error stack and check for lower level transport errors. For further details, turn on tracing and reexecute the operation. Turn off tracing when the operation is complete and follw the steps:
1.     Go to the windows machine that hosts the Oracle database server
2.     Go to Start -> Run -> Services.msc in windows. Locate OracleService (here OracleServiceORCL) and click on "Start" to start the oracle database service (if not already running)
3.     Once it is up and running, from the command prompt run the following:
tnsping < tnsalias >
(tnsalias entry you can find it in tnsnames.ora file)
ALSO CHECK THIS:
Seems like database is not up. It might be due to restarting machine and the instance is not set to autostart and it so not started munually after starting from services Screen.
Just goto Command prompt
1.     Set Oracle SID 
2.     C:>set oracle_sid=ORCL
3.     Now run Net start command. 
4.     C:>net start oracleserviceORCL

---------------------------------------------------------------------------------------

6.Error Message: ORA-03113 error is an unexpected end-of-file that occurred which could not be handled by SQL*Net 

Cause of Error:

All connections between a client software and an Oracle Server are 
created and managed by Oracle Networking or Net8. This is a two 
way connection between a Net8 Server (Listener) and a Net8 
client. After a connection is established between the two, this error 
may occur when the net8 server is no longer available, or can not 
respond to Net8 client requests due to problems with the Oracle 
Server.It can also be due to a network failure. If it occurs at startup 
a configuration or installation problem is a likely cause. If it occurs 
after a shutdown some defunct processes may be running.

Resolution:

Oracle Server Errors

If the failure occurs after a connection is established, a likely cause is a database server
 error. For example in my personal experiences all versions of Oracle server before 
8.1.6 are pretty unstable under Windows NT 4.0 with Service Pack 6.0 and frequent 
internal errors cause the server to discontinue its operation. In such cases one should 
see the alert log and will usually have to refer to Oracle Support. In the case mentioned 
above you should downgrade to Service Pack 5.

Net8 Server (Listener) Errors

This is when the listener fails to respond to Net8 client. The causes for such a failure are
numerous. Lack of memory on the server machine where the listener resides, or 
problems with the host operating system can cause the listener to fail. To make sure that
 the listener is working correctly one may use the Listener Control Utility (LSNRCTL). 
One may also restart listener using the host operating system facilities LSNRCTL or to 
recover from temporary errors.

The Network Connection Failure

This is when the network connection through the network protocol is no longer available. 
For example when using the TCP, a TCP/IP route must be available between the client 
machine and the server. This may be tested using the ping utility. There are also 
situations when a specified protocol is disabled for a machine, say when conflicting IP 
addresses occur or a router device or software fails. In such cases it may be possible to 
reach the listener through other protocols like Named Pipes. In such cases you should
 call for the network administrator to fix the problem or you can change the protocol in 
use. To change the protocol, change the protocol entry and the parameters for the 
connection string in use, in TNSNAMES.ORA or for the method in use (Oracle Names or 
external naming services.) Say in the TNSNAMES.ORA one may start using conn_nmp 
(Named Pipes) after conn_tcp fails. However bear in mind that in this case the listener 
must support NMP too for a connection to be established. To have listener support a 
new protocol one may use Net8 Assistant, LSNRCTL or edit listener.ora manually and
 restart the listener using the host operating system facilities.





7.Error Message:  ORA-00936 Error missing expression

Cause of Error:

You tried to execute an SQL statement but you omitted a part of the syntax.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

This error most commonly occurs when you try to execute an SQL SELECT statement and forget to the list of the columns in the SELECT statement.
For example, you tried to execute the following SELECT statement:
select
from suppliers;
You would receive the following error message.

You can correct the SELECT statement by including columns after the SELECT keyword. For example:
select supplier_id, supplier_name
from suppliers;




8.Error Message:  ORA-00604 :error occurred at recursive SQL level string

Cause of Error:

 An error occurred while processing a recursive SQL statement (a statement applying to internal dictionary tables).

Resolution

 If the situation described in the next error on the stack can be corrected, do so; otherwise contact Oracle Support.Many users of the new Oracle 11i find themselves being confronted by ORA-00604.   Oracle MOSC offers exceptional information regarding ORA-00604 in regards to the generate preventive maintenance work orders within 11.5.9 on all platforms.    It is explained that ORA-00604 occurs in Oracle Enterprise Asset Management, within the Generate Work Orders program as part of the bug 42325313.  In version 115.10.1159.5, this issue of ORA-00604 is filed within  PMEngine.java .   In order to fully resolve ORA-00604 , use the following steps provided to properly apply Patch 4232513 by MOSC:
1. Download and read the readme and pre-requisites
2. Apply Patch 4232513, but in a test environment
3. Confirm these file versions:
  • PMEngine.java 115.10.1159.5
4. try re-testing
5. Upon resolution, migrate the solution to the other environments as you see appropriate



 

9.Error Message:  ORA-00257: archiver is stuck. CONNECT INTERNAL only, until freed

Cause of Error:
While trying to archive a redo log file, the ARCH process encountered an error.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

This error can be caused when the destination device does not have enough storage space to store the redo log file.

Option #2

Check that the initialization parameter ARCHIVE_LOG_DEST in the initialization file is set correctly.
It may be helpful to check the archiver trace file for more details on the problem.
Note: If this problem is not resolved, Oracle will stop executing transactions.



10.Error Message:  ORA-01555: snapshot too old (rollback segment too small)


Cause of Error:This error can be caused by one of the problems, as described below.


Resolution :

The option(s) to resolve this Oracle error are:
Option #1
This error can be the result of there being insufficient rollback segments.
A query may not be able to create the snapshot because the rollback data is not available. This can happen when there are many transactions that are modifying data, and performing commits and rollbacks. Rollback data is overwritten when the rollback segments are too small for the size and number of changes that are being performed.
To correct this problem, make more larger rollback segments available. Your rollback data for completed transactions will be kept longer.
Option #2
This error can be the result of programs not closing cursors after repeated FETCH and UPDATE statements.
To correct this problem, make sure that you are closing cursors when you no longer require them.
Option #3
This error can occur if a FETCH is executed after a COMMIT is issued.
The number of rollback records created since the last CLOSE of your cursor will fill the rollback segments and you will begin overwriting earlier records




Wait For MOre .....................................