As the title describes, my program is throwing an UnauthorizedAccessException when attempting to create an Excel file with the ExcelLibrary Library, which is strange given my computer hasn't got any restrictions regarding that. My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelLibrary;
namespace ExcelTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
string cs = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=test1.mdb;";
ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
string[] x = new string[20];
for (int i = 1; i < x.Length; i++)
{
x[i] = "a";
}
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
OleDbConnection con = new OleDbConnection(cs);
con.Open();
string sql = "SELECT * FROM personas;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
ds.Tables.Add(dt);
}
private void button1_Click(object sender, EventArgs e)
{
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest", ds);
MessageBox.Show("creating excel");
}
}
}
Any ideas of what could the problem be? Thanks
EDIT: My exception log (it's in spanish, hope you don't mind):
System.UnauthorizedAccessException: Acceso denegado a la ruta de acceso 'C:\Users\spereyra\Documents\Visual Studio 2012\Projects\deleteme\ExcelTest'.
en System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
en System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
en System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
en System.IO.File.Open(String path, FileMode mode, FileAccess access, FileShare share)
en ExcelLibrary.CompoundDocumentFormat.CompoundDocument.Create(String file)
en ExcelLibrary.SpreadSheet.Workbook.Save(String file)
en ExcelLibrary.DataSetHelper.CreateWorkbook(String filePath, DataSet dataset)
en ExcelTest.Form1.button1_Click(Object sender, EventArgs e) en c:\Users\spereyra\Documents\Visual Studio 2012\Projects\deleteme\ExcelTest\Form1.cs:lĂnea 51
Found my error, I had specified the route to the file but forgot to type the filename and extension:
Instead of
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest", ds);
MessageBox.Show("creating excel");
I should have put
ExcelLibrary.DataSetHelper.CreateWorkbook("C:\\Users\\spereyra\\Documents\\Visual Studio 2012\\Projects\\deleteme\\ExcelTest\\myExcel.xls", ds);
MessageBox.Show("creating excel");
Related
Just starting to experiment with F#. I have this code working in C#:
using MySql.Data.MySqlClient;
using System;
using System.IO;
namespace SandboxExecuteReader
{
class Program
{
static void Main(string[] args)
{
MySqlConnection myConnection = new MySqlConnection();
MySqlCommand myCommand = new MySqlCommand();
if (!SQLdbOpen(myConnection, myCommand)) return;
DoWork(myCommand);
myConnection.Close();
return;
}
private static void DoWork(MySqlCommand myCommand)
{
myCommand.CommandText = "SELECT * FROM xxx.mytable";
using (var reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
string Field1 = reader.GetString(reader.GetOrdinal("Field1"));
string Field2 = reader.GetString(reader.GetOrdinal("Field2"));
string Field3 = reader.GetString(reader.GetOrdinal("Field3"));
Console.WriteLine("{0} {1} {2}", Field1, Field2, Field3);
}
}
}
private static bool SQLdbOpen(MySqlConnection myConnection, MySqlCommand myCommand)
{
/*
* Open Connection to SQL DB
*/
string ConnectionString = "server=(someIP); uid=Me; password=MyPass";
try
{
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
myCommand.Connection = myConnection;
}
catch (MySqlException E)
{
Console.WriteLine("Open Error: {0}", E.Message);
Console.WriteLine("Press RETURN to continue or CONTROL-C to abort");
Console.ReadLine();
return false;
}
return true;
}
}
}
Questions:
In C#, I add a reference to MySql.Data.dll. How do I do that in F#?
There seems to be something about #r ... where does that line go? Somewhere in the .fsproj file?
How would this code look in F#?
The first thing you need to decide is whether you are going to run this as a standalone script (.fsx file) or a project (consisting of .fs source files and a .fsproj project file).
If this is going to be a project, it works just like a C# project: you add a reference to MySql.Data.dll in your .fsproj file. If you're using Visual Studio, you can right-click on the project and find MySql.Data in NuGet via the "Manage NuGet Packages..." menu item.
If it's going to be a standalone script, you can add a NuGet reference to MySql by placing this line at the very top: #r "nuget: MySql.Data".
Converting your code from C# is a bit more involved, but your main function might look like this (assuming this is a .fs file):
open MySql.Data.MySqlClient
let sQLdbOpen (myConnection : MySqlConnection) (myCommand : MySqlCommand) =
// ...
true
let doWork (myCommand : MySqlCommand) =
// ...
()
[<EntryPoint>]
let main args =
use myConnection = new MySqlConnection()
use myCommand = new MySqlCommand()
if sQLdbOpen myConnection myCommand then
doWork myCommand
myConnection.Close()
0
(Caveat: I did this translation by eye, so it might not be exactly right.)
I need a help. I am trying to export the data to ADLS by converting the result set into the stream.
When I am trying this with a Console app, No error is thrown, But When I integrate this with the Script task enter code here Component It throws an error at runtime. Also After adding Azure classes Breakpoint is not hitting while debugging.
using System;
using System.Threading;
using Microsoft.Azure.Management.DataLake.Store;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.Azure.Authentication;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Text;
public class Program {
private static string adlsAccountName;
private static string tblName = "tblGrid";
DataTable dataTable = new DataTable();
public byte[] datared()
{
string connectionString = "Data Source=local;Initial Catalog=abc;Integrated Security=True";
string query = "select * from " + tblName;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
var a = Encoding.GetEncoding("iso-8859-1").GetBytes(ToByte(dataTable));
return a;
}
public static string ToByte(DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
public static void Main()
{
Program p = new Program();
var bytes = p.datared();
MemoryStream stream = new MemoryStream(bytes);
// Name of the Azure Data Lake Store
var adlsAccountName = "testadls08";
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
// Portal > Azure AD > Properties > Directory ID (aka Tenant ID)
var domain = "177cfeea-xxxx-xxx-853d-xxxx";
// Portal > Azure AD > App Registrations > App > Application ID (aka Client ID)
var clientId = "0e499fed-7f23-4b19-98ab-xxxxx";
// Portal > Azure AD > App Registrations > App > Settings > Keys (aka Client Secret)
var clientSecret = "6xxxxxxxxxxxxxxxxxxxxxxxx=";
var clientCredential = new ClientCredential(clientId, clientSecret);
var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;
var filepath = "/shared/" + tblName + ".txt";
var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
adlsFileSystemClient.FileSystem.Create(adlsAccountName, filepath, overwrite: true);
adlsFileSystemClient.FileSystem.Append(adlsAccountName, filepath, stream);
}
}
An exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.
UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.
InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
I was trying to salt password in asp.net web application mysql but its shows this error.While running getting the error.Please anyone tell me the error?
Error:
Server Error in '/' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'DemoPage.Default'.
Source Error:
Line 1: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoPage.Default" %>
Line 2:
Line 3: <!DOCTYPE html>
Source File: /Default.aspx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3163.0
Code default.aspx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebPage1
{
public partial class _default : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String name;
protected void Page_Load(object sender, EventArgs e)
{
DoSQLQuery();
}
protected void submit_click(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
String queryStr = "";
cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM webapp.userregistration WHERE username = #name and password=#pas", conn);
cmd.Parameters.AddWithValue("#name", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#pas", passwordTextBox.Text);
reader = cmd.ExecuteReader();
name = "";
while (reader.HasRows && reader.Read())
{
{
name = reader.GetString(reader.GetOrdinal("username")) + " " + reader.GetString(reader.GetOrdinal("password"));
}
//if the data matches the rows (username, password), then you enter to the page
if (reader.HasRows)
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("login.aspx", false);
}
else
{
passwordTextBox.Text = "invalid user";
}
}
reader.Close();
conn.Close();
}
private void DoSQLQuery()
{
try
{
}
catch (Exception e)
{
passwordTextBox.Text = e.ToString();
}
}
}
}
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using MySql.Data.MySqlClient;
namespace Student_Portal_Password
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string GetMd5Hash(string input)
{
MD5 md5Hash = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public void check()
{
if (txtid.Text == "")
{
MessageBox.Show("Please enter Student ID ", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
else if (txtpassword.Text == "")
{
MessageBox.Show("Please enter new password", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//check();
txtpassword.Text.Trim();
string hash = GetMd5Hash(txtpassword.Text);
string db = "server=localhost;uid=root;password=usbw;database=dum;";
MySqlConnection dbcon = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand(db);
dbcon.Open();
cmd.CommandText = "SELECT * FROM members;";
cmd.ExecuteNonQuery();
MessageBox.Show("Success!");
dbcon.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtid_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
}
}
A couple of things;
You're using ExecuteNonQuery for a Query. Try for example ExecuteReader instead.
You're not setting a connection for your DbCommand, so executing it won't find the database.
Try this instead;
MySqlConnection dbcon = new MySqlConnection(db);
string sql = "SELECT * FROM members";
MySqlCommand cmd = new MySqlCommand(sql, dbcon); //<-- pass connection to command
Your current code;
MySqlCommand cmd = new MySqlCommand(db);
...passes in the connection string as the SQL to execute, and does not associate the command with any database connection. That will give the error you're asking about.
Introduction:
I have SQL Server Express 2008 R2 installed with Advanced Services. I have created few reports using BI Design Studio and deployed them to the Server. If I access the reporting server using IE (http://Ser2008/Reports/) it works fine (I have to put in User Name/Password). I can view reports or fool around with the settings.
Problem:
On my local machine I created a winforms application with one form containing a ReportViewer control. On form load I'm running following code:
reportViewer1.ProcessingMode = ProcessingMode.Remote;
reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials =
new CustomCredentials("secret#123") {
UserName = "administrator",
Domain = "ser2008"
}.NetworkCredentials;
reportViewer1.ServerReport.ReportServerUrl = new Uri("http://ser2008/Reports/");
reportViewer1.ServerReport.ReportPath = "/Students/Attendance";
var l = new List<ReportParameter>();
l.Add(CreateParameter("UserId", "144"));
l.Add(CreateParameter("Class", "8"));
l.Add(CreateParameter("date_from", "2011-09-04"));
l.Add(CreateParameter("date_to", "2011-12-31"));
reportViewer1.ServerReport.SetParameters(l); //EXCEPTION THROWN HERE
reportViewer1.RefreshReport();
I get following exception:
The attempt to connect to the report server failed. Check your connection
information and that the report server is a compatible version. The request
failed with HTTP status 404: Not Found.
The stack trace is as follows:
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005
.Execution.RSExecutionConnection.MissingEndpointException
.ThrowIfEndpointMissing(WebException e)
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005
.Execution.RSExecutionConnection.ProxyMethodInvocation.Execute[TReturn]
(RSExecutionConnection connection, ProxyMethod`1 initialMethod, ProxyMethod`1 retryMethod)
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.
Execution.RSExecutionConnection.LogonUser(String userName, String password, String authority)
at Microsoft.Reporting.WinForms.ServerReport.get_Service()
at Microsoft.Reporting.WinForms.ServerReport.EnsureExecutionSession()
at Microsoft.Reporting.WinForms.ServerReport.SetParameters(IEnumerable`1 parameters)
at GridEditor.ReportViewerForm.btnRefresh_Click(Object sender, EventArgs e)
in D:\TestApp\ReportViewerForm.cs:line 79
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager
.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at GridEditor.Program.Main() in D:\TestApp\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback
, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
CustomCredentials:
public class CustomCredentials : IReportServerCredentials
{
public string UserName { get; set; }
public SecureString Password { get; set; }
public string Domain { get; set; }
#region ctor
public CustomCredentials(string password)
{
Password = new SecureString();
foreach (char c in password.ToCharArray())
Password.AppendChar(c);
}
#endregion
#region IReportServerCredentials Members
public bool GetFormsCredentials(out Cookie authCookie, out string userName
, out string password, out string authority)
{
throw new NotImplementedException();
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get { throw new NotImplementedException(); }
}
public System.Net.ICredentials NetworkCredentials
{
get { return new NetworkCredential(UserName, Password, Domain); }
}
#endregion
}
UPDATE:
I have found following exception also in some place in my log file:
System.Web.Services.Protocols.SoapException: The path of the item
'/Students/Attendance/_vti_bin/ListData.svc/$metadata' is not valid. The full
path must be less than 260 characters long; other restrictions apply. If the
report server is in native mode, the path must start with slash. --->
Microsoft.ReportingServices.Diagnostics.Utilities.InvalidItemPathException:
The path of the item '/Students/Attendance/_vti_bin/ListData.svc/$metadata' is
not valid. The full path must be less than 260 characters long; other
restrictions apply. If the report server is in native mode, the path must
start with slash.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl
.GetPermissions(String Item, String[]& Permissions)
In the end it was all trivial detail 8-)
I was using Report Manager url (http://ser2008/Reports/) where I was to use Report Server url (http://ser2008/ReportServerXp/).
Well, you should implement IReportServerCredential, and code example as follow :
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName,_PassWord,_DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
then use this as follows:
IReportServerCredentials irsc = new CustomReportCredentials(userid,password, domain);
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
the other code to set ServerReport property omit. hope you have a good day.