Quantcast
Channel: Access Databases and AccessDataSource Control
Viewing all 518 articles
Browse latest View live

online tutorial

$
0
0

Hi,

I know enough about sql server and I found there's a lot of differences between ms access database and sql server.

  • If any one know a online tutorial about

variables, join, queries, top clause and so on in microsoft access please let me know.

  • and if you know tutorials about asp.net with oledb let me know please.

thanks in advance


Copying data from one table to another

$
0
0

I'm taking over a database from another employee. It wasn't designed properly, hence I'm trying to redesign it.

We have documents, which contain the name/number/address/etc of the person who made that document.
This person, the applicant, is often repeated, hence it's best to have a table just for applicants.

This caused all sorts of issues with dirty data. Spaces at the end, in the beginning, capitalisation, punctuation, everything. I spent 6 hours and cleaned up the data.
Now I just need to restructure. 

OLD STRUCTURE:

Documents:
- ID
- ApplicantName
- ApplicantPhone
- ApplicantCity

NEW STRUCTURE:

Documents:
- ID
- ApplicantID
- ApplicantName (Legacy)
- ApplicantPhone (Legacy)
- ApplicantCity (Legacy)

Applicants:
- ID
- Name
- Phone
- City 

The issue:

I need a query that will look at DOCUMENTS and see which name was in the legacy ApplicantName column. It will then search for that name in the APPLICANTS table, and put the associated ID in the DOCUMENTS.APPLICANTID column.

How would a query like this go? I'm having trouble figuring it out in my head.

Once the ID is populated, the legacy columns can be deleted.

No value given for one or more required parameters Error in host but not in localhost

$
0
0

Hi,

I get this error in host

No value given for one or more required parameters.


but it works like a charm in local what's the problem?


Thanks a lot

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

excuse me I upload my database again and it's ok now.




1 Dataset from 2 different Access databases

$
0
0

Hello,

I have 2 different ACCESS databases, employees & tools.  Is there a way to pull fields from both databases with 1 query string? 

Something like: SELECT Employee.empName, Employee.Emp#, Tool.toolID, Tool.desc  Employee.Employee Inner Join Tools.ToolEmp on Employee.Employees.Emp# = Tools.ToolsEmp.Emp# Right Outer Join Tools.Tool ON Tools.ToolEmps.toolID = Tools.Tool.toolID

Each tool can have many different employees using it. 

Employees db  = 1 table (Employee) with these fields: empName, emp id, emp#

Tools db = 1 table (Tool) of different types of tools with these fields: toolID, tool desc, tool dept
Tools db 2nd table (ToolEmps)  = toolID, emp#

Looking to get 1 dataset with a list of the employee and the tools they are assigned.

Since it's in ACCESS could I do this even though there would be different connection strings for both?

I know the SELECT statement probably isn't correct with the JOINS but could this type of thing work?

JS

Unable to view datasheet view of sharepoint dataview on IE10

$
0
0

Hello,

I get below error when tried to edit dataview in datasheet view.

"A datasheet component compatible with Microsoft Sharepoint Foundation is not installed."

Have done with ActiveX componant and using 32 bit of IE10. Please suggest if any other option is there.

Thanks...

Syntax error (missing operator) in query expression

$
0
0

Hi

 

I have an issue in Access when i try to updata a table called User. I have made a form called frmGRPE with text fields where i retrives information (user information) from a database called tblUser. I can retrive the information from the database, but the problem starts when i trie to save the changes in the form back in to the databse. I use the function UPDATE for this and i can almost get this to work. Below is two expressions where the first gives me syntax error and the other inputs ME.txtEN.Value into the correct location in the databse(obviously since i put ME.txtEN.Value inside '  '.

 

  1. CurrentDb.Execute "UPDATE tblUser " & "SET Employee_Number= Me.txtEN.Value" & "Where [User_ID]=" & Me.txtUser.Value
  2. CurrentDb.Execute "UPDATE tblUser " & "SET Employee_Number= 'Me.txtEN.Value'" & "Where [User_ID]=" & Me.txtUser.Value

 

My question is why does this this work (second expression) when i SET sepcific value from code intot the databse, but when i try to get this value from the txtEN field in the form form i get syntax error?!!

 

Thanx in advance for any help on this issue!!

Requirement for defining and using an object variable as TableDef

$
0
0

I've been pursuing to change the paths of linked files through code in an ASP.NET (2.0 I suppose) page.

My first attempt on reading and manipulating data from the MSysObject failed at the last inch as I where unable to update/write the field content after reading and manipulating it. Despite setting permissions for the system object to full access.

After further research, I'd like to have a go at using the TableDef collection, but was stopped early in the process by the error message "Type 'TableDef' is not defined".

Offending line; 

"Dim TableDef_Collection As TableDef"

I thought another namespace (in addition to "System.Data.OleDb") import might be required, but can't find nothing on-line that helps me past this initial step, and now I've just wasted to many brain cells and time on not getting anywhere on my own, so here is the question;

What are the requirements for defining and using a collection variable as TableDef in a .aspx-page?

Current preparation;

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="utf-8" %><%@ Import Namespace="System.Data.OleDb" %>

I've also added lots of more namespaces I thought could be (remotely) connected, but had no luck with that ...

Delete image from access db.

$
0
0

Hello. In my upload gallery i have (mdb access), i upload and insert image in. 

How can i have a "delete" button, when i show the data in gridview?

My code is:

publicpartialclass_upload : System.Web.UI.Page

{

    // Access Database oledb connection string

    // Using Provider Microsoft.Jet.OLEDB.4.0

    String connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+HttpContext.Current.Server.MapPath("App_Data/db1.mdb");

    // Object created for Oledb Connection

    OleDbConnection myAccessConnection;

    protectedvoid openAccessConnection()

    {

        // If condition that can be used to check the access database connection

        // whether it is already open or not.

        if(myAccessConnection.State == ConnectionState.Closed)

        {

            myAccessConnection.Open();

        }

    }

    protectedvoid closeAccessConnection()

    {

        // If condition to check the access database connection state

        // If it is open then close it.

        if (myAccessConnection.State == ConnectionState.Open)

        {

            myAccessConnection.Close();

        }

    }

    protectedvoid Page_Load(object sender,EventArgs e)

    {

        myAccessConnection = newOleDbConnection(connStr);

        if (!IsPostBack)

        {

            displayImages();

        }

    }

    protectedvoid btnUpload_Click(object sender,EventArgs e)

    {

        int imageSize;

        string imageType;

        Stream imageStream;

        // Gets the Size of the Image

        imageSize = fileImgUpload.PostedFile.ContentLength;

        // Gets the Image Type

        imageType = fileImgUpload.PostedFile.ContentType;

        // Reads the Image stream

        imageStream = fileImgUpload.PostedFile.InputStream;

        byte[] imageContent = newbyte[imageSize];

        int intStatus;

        intStatus = imageStream.Read(imageContent, 0, imageSize);

        

        OleDbCommand myCommand = newOleDbCommand("insert into tblImg(img_title,img_stream,img_type) values(@img_title,@img_stream,@img_type)", myAccessConnection);

        // Mark the Command as a Text

        myCommand.CommandType = CommandType.Text;

        // Add Parameters to Command

        OleDbParameter img_title = newOleDbParameter("@img_title", OleDbType.VarChar);

        img_title.Value = txtImgTitle.Text;

        myCommand.Parameters.Add(img_title);

        OleDbParameter img_stream = newOleDbParameter("@img_stream", OleDbType.Binary);

        img_stream.Value = imageContent;

        myCommand.Parameters.Add(img_stream);

        OleDbParameter img_Type = newOleDbParameter("@img_type", OleDbType.VarChar);

        img_Type.Value = imageType;

        myCommand.Parameters.Add(img_Type);

        try

        {

            openAccessConnection();

            myCommand.ExecuteNonQuery();

            closeAccessConnection();

            Response.Redirect("upl.aspx");

        }

        catch (Exception exc)

        {

            Response.Write("Insert Failure. Error Details : "+ exc.Message.ToString());

        }

        

    }

    publicvoid displayImages()

    {

        try

        {

            openAccessConnection();

            OleDbCommand myCommand = newOleDbCommand("select * from tblImg", myAccessConnection);

            // Mark the Command as a Text

            myCommand.CommandType = CommandType.Text;

            OleDbDataAdapter myAdapter = newOleDbDataAdapter(myCommand);

            DataSet myDataSet = newDataSet();

            myAdapter.Fill(myDataSet);

            if (myDataSet.Tables[0].Rows.Count>0)

            {

                GridView1.DataSource = myDataSet;

                GridView1.DataBind();

            }

            closeAccessConnection();

        }

        catch (Exception exc)

        {

            Response.Write("Data Retrival Failure. Error Details : "+ exc.Message.ToString());

        }

    }

    publicstring imageURL(string img_id)

    {

        return ("retrieveImages.aspx?id="+ img_id);

    }

}

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

 <div>

                Image Title:<asp:TextBoxID="txtImgTitle"runat="server"></asp:TextBox>

            </div>

            <div>

                Browse Image:<asp:FileUploadID="fileImgUpload"runat="server"/>

            </div>

            <div>

                <asp:ButtonID="btnUpload"runat="server"Text="Save"OnClick="btnUpload_Click"/></div>

        </div>

        <br/>

        <br/>

        <div>

            <asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"CellPadding="5"

                GridLines="None"ShowHeader="False">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:ImageID="imgSaved"runat="server" ImageUrl='<%# imageURL(DataBinder.Eval(Container.DataItem, "img_id").ToString())%>'

                                AlternateText='<%#DataBinder.Eval(Container.DataItem,"img_title")%>'Height="80px"  Width="100px"/>

                            <asp:HyperLinkID="HyperLink11"rel="lyteshow[map]"runat="server" 

                                Width="160px" Text='<%# Eval("img_title") %>'   ></asp:HyperLink>

               

                       

                        </ItemTemplate>

                    

                    

                    </asp:TemplateField>

             </Columns>

            </asp:GridView>

        </div>

        

        

        <div>

            

            

            <br/>

        </div>

        </div>

    <asp:AccessDataSourceID="AccessDataSource1"runat="server" 

        DataFile="~/App_Data/db1.mdb"SelectCommand="SELECT * FROM [tblImg]">

    </asp:AccessDataSource>

    </form>


Change Datasource in dll

$
0
0

We have a number of different applications based mainly on 3 distinct data backends.  I was thinking about building 3 distinct dlls to use as the data source and business layer for multiple apps, some MVC, some web forms, some windows forms.  My main question is if I was to create a dll and then reference it in the projects can you change the connection at runtime or will I need to compile a version for production, one for test, and one for development?

or is there a better way to share the data layer/ model across different applications?

New on asp.net try to add data to Access Database Help....

$
0
0

Hi im very new on asp.net im trying to insert data from a textbox to a database using this code adn works the problem is how can i chek if a duplication exist try very differents options but im very new to this.

 Sub Button1_Click(sender AsObject, e AsEventArgs)Handles Button1.Click

 

 

 Dim ConnString AsString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|NOVABRO1.accdb"

 Dim SqlString AsString = "Insert Into NEWRECEIVE (COMPANY_NAME, WO, RECEIVED_FROM, SHIPTO,DATE_RECEIVED, PO, BLN, SHIP_VIA) Values (?,?,?,?,?,?,?,?)"

  Using conn AsNewOleDbConnection(ConnString)

    Using cmd AsNewOleDbCommand(SqlString, conn)

                cmd.CommandType =CommandType.Text

                cmd.Parameters.AddWithValue("COMPANY_NAME", CompanyTextBox.Text)

                cmd.Parameters.AddWithValue("WO", MainWOTextBox.Text)

                cmd.Parameters.AddWithValue("RECEIVED_FROM", ReceivedTextBox.Text)

                cmd.Parameters.AddWithValue("SHIPTO", ShipToTextBox.Text)

                cmd.Parameters.AddWithValue("DATE_RECEIVED", DateTextBox.Text)

                cmd.Parameters.AddWithValue("PO", POTextBox.Text)

                cmd.Parameters.AddWithValue("BLN", BLNTextBox.Text)

                cmd.Parameters.AddWithValue("SHIP_VIA", ShipTextBox.Text)

                conn.Open()

                cmd.ExecuteNonQuery()

            EndUsing

       EndUsing

Insert image into access database

$
0
0

Insert image into access database

Dim con1 As OleDbCommand
Dim str1 As String

con1 = New OleDbCommand
con1.Connection = cnn


Dim img As String

For Each g1 As GridViewRow In GridView1.Rows
img = g1.Cells(1).Text

cnn.Open()

str1 = "INSERT INTO Table1(img) VALUES(@img)"
Dim com As New OleDbCommand(str1, cnn)

com.Parameters.AddWithValue("@img", img)
com.ExecuteNonQuery()
com.Dispose()
cnn.Close()
Next

please help..

Calculate Free Time Slot

$
0
0

I am reporting a educational domain teacher's master table . The teacher commences multiple lectures in one day and each batch has got a unique batchid, along with this the table logs lecture starttime lecture end time for their respective battches
Following is the schema of my table ('M/W/F/' means Monday Wednesday Friday &amp; 'T/T/S'/ means Tuesday Thursday and Saturday)

ID TEACHERID STARTDATE  EXPECTEDENDDATE         DAYS    STARTTIME   ENDTIME
3   1254    2007-11-28  2008-01-21              M/W/F/  9:00 AM     10:00AM
4   1254    2008-02-20  2008-03-17             M/W/F/   11:30 AM    1:00PM
5   1315    2008-11-17  2008-12-17             T/T/S/   2:00 PM     3:30PM
6   1315    2008-11-05  2008-12-05            T/T/S/    12:00 AM    1:30PM
8   1155    2008-04-18  2008-04-30            M/W/F/    10:30 AM    12:00AM
9   1514    2008-04-01  2008-08-06            T/T/S/    12:30 PM    1:00PM

Consider 1254 teacher , he is taking a batch from 9:00 AM to 10:00AM
then 11:30 AM  to  1:00PM so he has 10:00AM to 11:30 AM free slot . How do I fetch it for each teacher if I give teacherID as input paramater .
I want to display the report in Asp.net front end page.

SQL Error

$
0
0

The following error. Research suggests it's caused by using a reserved word. I can't imagine what reserved word it would be. I've encased everything in square brackets. What am I missing?

IErrorInfo.GetDescription failed with E_FAIL(0x80004005).


Happens from the following code:

SELECT t.[TIMESHEETID] as [ID], t.[PERIOD] as [Period], u.[USERNAME] as [Employee], DATENAME(MM, t.[DATEWORKED]) + RIGHT(CONVERT(VARCHAR(12), t.[DATEWORKED], 107), 9) AS [Date Worked], t.[PAYTYPEDESC] as [Pay Type], t.[HOURS] as [Hours], t.[WORKORDERDESC] as [Work Order], t.[LUMPSUM] as [LSum], DATENAME(MM, t.[DATEENTERED]) + RIGHT(CONVERT(VARCHAR(12), t.[DATEENTERED], 107), 9) as [Date Entered], t.[SIGNED] as [Signed], t.[DESCRIPTION] as [Description],

    SUBSTRING( (SELECT ', ' + RTRIM(e.[ASSET_NUMBER])
                FROM [EquipmentTimeEntry] as eq
                join [Mirror_EquipmentList] as e on e.[ASSET_NUMBER] = eq.[EQUIPID]
                WHERE eq.[TIMESHEETID] = t.[TIMESHEETID]
                GROUP BY e.[ASSET_NUMBER]
                FOR XML PATH('') ), 3, 200000) as [Equipment]

FROM [Timesheets] t, [Users] u
WHERE t.[EMPLOYEEID] = u.[EMPLOYEEID] AND [HIDDEN] = 0 AND [SENT] = 0
ORDER BY t.[signed], t.[TIMESHEETID] DESC

Unable to connect

$
0
0

Hi,
I am to connect to Access 2013 DB using this

<connectionStrings><add name="AC13conn2" Provider="Microsoft.ACE.OLEDB.12.0;Data" Source="C:\inetpub\DB1.accdb" Jet="" OLEDB:Database="" Password="??????";/></connectionStrings>



in the VS 2013 project but I have these errors. why?

Error    1    Object reference not set to an instance of an object.        0    0    App16
Error    2    Character ';', hexadecimal value 0x3b is illegal in an XML name.    C:\App16\App16\Web.config    15    140    App16
Error    3    Namespace prefix 'OLEDB' is not defined.    C:\App16\App16\Web.config    15    105    App16
Error    10    Application Configuration file "Web.config" is invalid. Name cannot begin with the ';' character, hexadecimal value 0x3B. Line 15, position 140.    C:\App16\App16\Web.config    15    140    App16

Insert into Access DataBase in .CS file

$
0
0

I want to capture users as they login and creat a record in an Access database. Since there is a .cs file associated with the Login page and I'm using a Master page for the Login page, I can't use the AccessDatasource1.Insert() on the Login page and I don't know how to do it in the .cs file.  Any ideas?

Ray


Unable to open DB

$
0
0

Hi,
I have this in VS 2013 project

string connectString ="Server=(local);Integrated Security=true";
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
                        builder.AttachDBFilename = @"C:\inetpub\DB1.accdb;Jet OLEDB:Database Password=??????";
                        SqlConnection conn = new SqlConnection(builder.ConnectionString);
                        SqlCommand cmd2;

                        conn.Open();
                        try
                        {
                            cmd2 = new SqlCommand("...", conn);
                            ...

but when running the deployed project, I get this below. why?

Server Error in '/App16' Application.

CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file C:\inetpub\DB1.accdb;Jet OLEDB:Database Password=?????? failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.Data.SqlClient.SqlException: CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file C:\inetpub\DB1.accdb;Jet OLEDB:Database Password=?????? failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

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: 



[SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file C:\inetpub\DB1.accdb;Jet OLEDB:Database Password=?????? failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6777754
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6778255
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +878
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1162
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +72
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +6781425
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +103
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2105
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1089
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
   System.Data.SqlClient.SqlConnection.Open() +239
   Start._Default.Page_Load(Object sender, EventArgs e) +771
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

  


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408  





New field in query (Access 2010)

$
0
0

Hi,

I need to add three columns in a query giving the result for Month 1, Month 2 and Month 3, example of query Select:

EmployeeID, EmployeeUserID, EmployeeName, EmployeeDept, Sum(Total), PayMonth1, Pay Month2, PayMonth3

I am Ok to write the WHERE Statement to give me the result of the three previous months:

[code] WHERE (((Tbl_Pay_Advisor.Month) Between DateAdd("m",-3,[Enter_Month]) And DateAdd("m",-1,[Enter_Month]))) [/code]

but How do I get the results in the query in individual columns? This is to put in place a Quality Check and visualy check if teh data is in fact for teh three previous months.

Thanks,

type mismatch when importing Excel file (access 2010)

$
0
0

Hi,

I am getting the message (Type mismatch) every time I try to import a spreadsheet regardless if is to add into a extint table or to create a new table, is tehre any ideas why this could be?

Thanks,

ExecuteNonQuery not executing.

$
0
0

For some reason, I can not get the ExecuteNonQuery to fire the SQL update. The page loads without incident, no errors, nothing. The other database connections, i.e. the adapter, work fine. Not sure why the ExecuteNonQuery is not forcing the update to the database to occur.

protected void btnMeterEmail_Click(object sender, EventArgs e)
    {

        //retrieve session variable (datatable) storing IDs which have been clicked on...
        //strID is the new ID string with all of the machineIDs in it formatted for SQL query, while strIDs is the datatable with the raw data in it
        string strID = "";
        DataTable strIDs = (DataTable)Session["tblSelected"];
        foreach (DataRow row in strIDs.Rows)
        {
            if (strID == "")
            {
                strID = row["machineID"].ToString();
            }
            else
            {
                strID = strID + "," + row["machineID"].ToString();
            }
        }

        string conStr = "DSN=MyDB;PWD=password;";
        OdbcConnection conAccessDB = new OdbcConnection(conStr);
        conAccessDB.Open();
        DataTable dt = new DataTable();

        OdbcDataAdapter da = new OdbcDataAdapter("SELECT * FROM Contracts WHERE ID IN (" + strID + ") Order By BeginDate ASC", conAccessDB);
        da.Fill(dt);

        // Retrieve distinct email accounts in datatable from Contracts DB with correctly selected IDs
        DataView dvEmails = new DataView(dt);
        DataTable distinctValues = dvEmails.ToTable(true, "Email");

        // Display datatable with meters receiving an email for meter reading
        gvMeters.DataSource = dt;
        gvMeters.DataBind();
        conAccessDB.Dispose();

        // Define new mailmessage (from, to)
        MailMessage mMailMessage = new MailMessage("...");

        //set subject
        mMailMessage.Subject = "Meter Reading Form";

        string strAdminEmail = "";
        string strSystemIDsforAdminEmail = "";
        //run this for each so each email address receives their list of meter read requests
        foreach (DataRow row in distinctValues.Rows)
        {

            string strURL = "";
            DataRow[] result = dt.Select("Email='" + row["Email"].ToString() + "'");

            //create string so that each email address is bundled together to be sent via email
            foreach (DataRow row1 in result)
            {
                strURL = strURL + "<a href='http://www.mywebsite.com/Meters.aspx?SysID=" + row1["SystemID"].ToString() + "&Name=" + row1["Contact"].ToString() + "&Company=" + row1["Customer"].ToString() +"&Email=" + row1["Email"].ToString() + "&Model=" + row1["Model"].ToString() +"&City=" + row1["City"].ToString() + "&State=" + row1["State"].ToString() +"&Phone=" + row1["Phone"].ToString() + "&Location=" + row1["Location"].ToString() + "'>ID: " + row1["SystemID"].ToString() +", Model: " + row1["Model"].ToString() + ", Location: " + row1["Location"].ToString() +"</a><BR /><BR />" + Environment.NewLine;
                //create string for updating LastNoticeDate in SQL statement
                if (strSystemIDsforAdminEmail == "")
                {

                    strSystemIDsforAdminEmail = strSystemIDsforAdminEmail + row1["SystemID"].ToString();
                }
                else
                {
                    strSystemIDsforAdminEmail = strSystemIDsforAdminEmail + "," + row1["SystemID"].ToString();
                }

            }

            //Capture strURL so we can bundle them all into strAdminEmail (to send admin an email of all units being sent email)
            strAdminEmail = strURL + strAdminEmail;

            //set email body
            mMailMessage.Body = "Thank you ....<br /><br />" + strURL;

            // check email type HTML or NOT
            mMailMessage.IsBodyHtml = true;

            // define new SMTP mail client
            SmtpClient mSmtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential("");
            mSmtpClient.Host = "smtp.mywebsite.com";
            mSmtpClient.UseDefaultCredentials = false;
            mSmtpClient.Credentials = basicCredential;

            //send email using defined SMTP client
            mSmtpClient.Send(mMailMessage);

        }

        // Send administrator an email of all units sent an email.
        // Define new Administrator mailmessage (from, to)
        MailMessage mMailAdminMessage = new MailMessage();

        //set subject
        mMailAdminMessage.Subject = "Meter Reading Sent";

        //set email body
        mMailAdminMessage.Body = "The following units were sent emails from the meter website:<br /><br />" + strAdminEmail + "IDs: " + strSystemIDsforAdminEmail +"Update Contracts Set LastNoticeDate='" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/"+ DateTime.Now.Year.ToString() + "' WHERE SystemID='" + strSystemIDsforAdminEmail + "'";

        // check email type HTML or NOT
        mMailAdminMessage.IsBodyHtml = true;

        // define new SMTP mail client
        SmtpClient mAdminSmtpClient = new SmtpClient();
        NetworkCredential basicAdminCredential = new NetworkCredential("...");
        mAdminSmtpClient.Host = "smtp.mywebsite.com";
        mAdminSmtpClient.UseDefaultCredentials = false;
        mAdminSmtpClient.Credentials = basicAdminCredential;

        //send email using defined SMTP client
        mAdminSmtpClient.Send(mMailAdminMessage);

        // Reset LastNoticeDate to current --> NOT FUNCTIONING PART
        string strAdminUpdateDate = "Update Contract Set astNoticeDate='" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/"+ DateTime.Now.Year.ToString() + "' WHERE SystemID='" + strSystemIDsforAdminEmail + "'";
        try
        {
            using (OdbcConnection conUpdateLastOrderDate = new OdbcConnection(conStr))
            {
                conUpdateLastOrderDate.Open();
                try
                {
                    using (OdbcCommand com = new OdbcCommand(strAdminUpdateDate, conUpdateLastOrderDate))
                    {
                        com.ExecuteNonQuery();
                    }
                }
                catch (OdbcException odEx)
                {
                    throw odEx;
                }
                conUpdateLastOrderDate.Close();
                conAccessDB.Close();
            }
        }
        catch (OdbcException OdEx)
        {
            throw OdEx;
        }

    }

Retrieving the COM class factory for component with CLSID failed due to the following error: 80070005 access is denied

$
0
0

My application is install in Windows Server 2008 R2 64 bit machine. But MS Office-7 32 bit install in that server. MS Excel application permission has been given to Every User from DCOM Config. This Configuration was fine to create an excel from my asp.net web application.

But to upload Excel data through my application was not work on that time due to 64 bit machine and MS Office 32 bit configuration. To solve this problem, I Install "AccessDatabaseEngine_x64" software in Server and give MS Excel Application permission to"Every One" from DCOM Config.

Now my upload excel problem has been gone. But create an excel from my asp.net web application not work.

Please help me. thank you.

Viewing all 518 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>