When exiting Excel Application in Windows Forms, the parent form closes too - windows-forms-designer

I am using Microsoft.Office.Interop.Excel to open an excel application within a panel. However, whenever I close Excel in the panel, it closes the parent form as well. Currently using a button to open excel in the panel, but not sure how to keep the parent form open when excel is closed.
private void button1_Click_1(object sender, EventArgs e)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
excelApp.ScreenUpdating = true;
excelApp.EnableAutoComplete = false;
object misValue = System.Reflection.Missing.Value;
excelWorkBook = excelApp.Workbooks.Add(misValue);
IntPtr excelHwnd = new IntPtr(excelApp.Application.Hwnd);
SetParent(excelHwnd, pnl_ProjectDoc.Handle);
excelApp.WindowState = XlWindowState.xlMaximized;
}

Related

Open link in a new window in ajax panel on server side

I have asked this question before, but got no answer that worked.
This is a buttonclick event that should initiate the download:
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
SendFileDownload(file);
}
One of the solutions that was offered was opening a link in a new window and have the window on page load initiate the download there with this piece of code:
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
// SendFileDownload(file); dont call it here , call it in the other window
string url = "PopupFileDownload.aspx?file="+file;
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
}
This did not work. I tried doing something similar since I am using the Telerik Ajax Panel
ajaxPanel.ResponseScripts.Add("window.open('DownLoadPopup.aspx?file='" + file + "'', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');");
But this also did not work. the command was executed with no effect.
How can I send a file to the user without sacrificing the Ajax panel?
If your button's inside an ASP.NET Ajax UpdatePanel you could turn off the ajax for just the download button
ScriptManager.RegisterPostBackControl(btnDownload);
If you're using Telerik Ajax controls, you can use the following code to pop up a RadWindow.
Make sure you've got a RadScriptManager and a RadAjaxManager on your page before your RadAjaxPanel...
Then add a RadWindowManager inside your RadAjaxPanel like this...
<telerik:RadWindowManager runat="server" ID="rwm" Modal="true" Skin="Default" AutoSize="true" />
Then in your code, you can do this...
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
rwm.Windows.Clear();
var rWin = new RadWindow();
rWin.ID = "Name of my window";
rWin.NavigateUrl = string.Format("~/DownLoadPopup.aspx?file={0}", file);
rWin.Width = Unit.Pixel(1000);
rWin.Height = Unit.Pixel(600);
rWin.VisibleOnPageLoad = true;
rwm.Windows.Add(rWin);
}
Adjust the path to your DownLoadPopup.aspx and the properties of the RadWindow as necessary.

Read from web service

I have this web service
http://currencies.apps.grandtrunk.net/currencies
How can I open it and view its data inside void page_load function on visual studio 2010?
Sorry i'm beginner with ASP.net.
That isn't really a web service, it seems to be newline-separated values in a text file served over HTTP.
Just use an HttpClient to download the data and split the result on newline.
In Page Load Event
if(!IsPostBack)
{
System.Net.WebClient client = new System.Net.WebClient();
string data = client.DownloadString("http://currencies.apps.grandtrunk.net/currencies");
List<string> data1 = data.Split('\n').ToList();
DropDownList1.DataSource = data1;
DropDownList1.DataBind();
}
Dropdown Index change event
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = DropDownList1.SelectedIndex;
string selectedValue = DropDownList1.SelectedValue;
string selectedText = DropDownList1.SelectedItem.Text;
}
Add AutoPostBack event in dropdown control properties
Thanks
Jai
You can use WebClient Class and DownloadString method
using (var client = new WebClient())
{
var list = client.DownloadString("http://currencies.apps.grandtrunk.net/currencies");
var values= list.Split(Convert.ToChar("\n"));
}

Crystal Report Viewer - Logon prompt

I have some Crystal Reports off a customer which I need to link to an ASP.NET application we are creating. I have the following code:
LINQDataContext dc = new LINQDataContext();
Order o = dc.Orders.Where(a => a.ID == long.Parse(Request.QueryString["OrderID"])).Single();
SqlConnectionStringBuilder bld = new SqlConnectionStringBuilder(dc.Connection.ConnectionString);
CrystalReportSource src = new CrystalReportSource();
src.ID = "test";
ConnectionInfo myConnectionInfo = new ConnectionInfo();
myConnectionInfo.ServerName = bld.DataSource;
myConnectionInfo.DatabaseName = bld.InitialCatalog;
myConnectionInfo.UserID = bld.UserID;
myConnectionInfo.Password = bld.Password;
src.Report.FileName = o.SalesPersonObject.GetType().GetProperty(Request.QueryString["DeliveryNoteType"]).GetValue(o.SalesPersonObject, null).ToString();
ParameterDiscreteValue param = new ParameterDiscreteValue();
param.Value = long.Parse(Request.QueryString["OrderID"]);
src.ReportDocument.ParameterFields[0].CurrentValues.Add(param);
CrystalReportViewer vw = new CrystalReportViewer();
src.ReportDocument.SetDatabaseLogon(bld.UserID, bld.Password);
vw.HasToggleGroupTreeButton = false;
vw.AutoDataBind = true;
vw.Height = 1268;
vw.Width = 1000;
vw.HasPrintButton = true;
vw.PrintMode = PrintMode.Pdf;
vw.ReportSource = src;
//vw.EnableDatabaseLogonPrompt = false;
vw.HasToggleParameterPanelButton = false;
vw.HasCrystalLogo = false;
vw.RefreshReport();
plcReport.Controls.Add(vw);
However, even though I'm setting the username/password using the SetDatabaseLogon method, I'm still getting a prompt to enter the database login details, or more specifically to enter the password. I've tried using vw.EnableDatabaseLogonPrompt = true, but that gives me a database login issue.
Any ideas?
See how I helped another SO user who was facing a similar problem .I hope you will be able to get something valuable.
Reference
For your connection, use the OLE driver; don't use the native SQL driver. Not sure if that's your current issue, but my experience has been that if I use the native driver it works okay in development, but then always prompts for a login in production.
You can try the the following code:
using CrystalDecisions;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
public partial class ClientsByOpeningDate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument rpt = new ReportDocument();
rpt.Load(Server.MapPath("ClientsByOpenDate.rpt"));
rpt.SetDatabaseLogon("myUserLogin", "mypassword", #"Server", "Database");
CrystalReportViewer1.ReportSource = rpt;
}
}
}

CRUD Operations with DetailsView and EntityDataSource in Custom Server Control

I am not a big fan of ASPX pages, drag-and-drop and so on. I'm building a portal with a single Default.aspx and every other thing is custom web part controls or server controls that other developers can build in compiled dll and users can upload to the portal themselves to add features to the portal. I've been battling with DetailsView crud operations with entitydatasource. I did a test.aspx page with drag and drop and everything worked fine but with 100% code behind, nothing is. No error is displayed but data are not being persisted to database. I tried catching the onUpdating event of the detailsview and yes the event was fired and I could enumerate the data submitted but why is it not persisted to database? Hope someone can help with this.
Here's my code (trying to create everything from codebehind and add them to placeholders on the page just for testing purpose before I move everything to web part):
public partial class Test : System.Web.UI.Page
{
private EntityDataSource eds = new EntityDataSource();
public DetailsView dtlview = new DetailsView();
protected void Page_Load(object sender, EventArgs e)
{
//Initialize Datasource
eds.ConnectionString = "name=DBEntities";
eds.DefaultContainerName = "DBEntities";
eds.EnableDelete = true;
eds.EnableFlattening = false;
eds.EnableInsert = true;
eds.EnableUpdate = true;
eds.EntitySetName = "EmailAccounts";
Controls.Add(eds);//I don't know if this is necessary
//Create DetailsView and configure for inserting on default
dtlview.DataSource = eds;
dtlview.AutoGenerateInsertButton = true;
dtlview.AutoGenerateDeleteButton = true;
dtlview.AutoGenerateEditButton = true;
dtlview.AutoGenerateRows = false;
dtlview.DefaultMode = DetailsViewMode.Insert;
dtlview.AllowPaging = true;
dtlview.DataKeyNames = new string[] { "ID" };
dtlview.AllowPaging = true;
//Create fields since autogeneraterows is false
BoundField bfID = new BoundField();
bfID.DataField = "ID";
bfID.HeaderText = "ID:";
BoundField bfUserID = new BoundField();
bfUserID.DataField = "UserID";
bfUserID.HeaderText = "User ID:";
BoundField bfDisplayName = new BoundField();
bfDisplayName.DataField = "DisplayName";
bfDisplayName.HeaderText = "Display Name:";
BoundField bfEmailAddress = new BoundField();
bfEmailAddress.DataField = "EmailAddress";
bfEmailAddress.HeaderText = "Email:";
BoundField bfPassword = new BoundField();
bfPassword.DataField = "Password";
bfPassword.HeaderText = "Password:";
BoundField bfOutgoingServer = new BoundField();
bfOutgoingServer.DataField = "OutgoingServer";
bfOutgoingServer.HeaderText = "Outgoing server:";
BoundField bfIncomingServer = new BoundField();
bfIncomingServer.DataField = "IncomingServer";
bfIncomingServer.HeaderText = "Incoming Server:";
CheckBoxField chkfIsDefault = new CheckBoxField();
chkfIsDefault.DataField = "IsDefault";
chkfIsDefault.HeaderText = "Is Default?";
dtlview.Fields.Add(bfID);
dtlview.Fields.Add(bfUserID);
dtlview.Fields.Add(bfDisplayName);
dtlview.Fields.Add(bfEmailAddress);
dtlview.Fields.Add(bfPassword);
dtlview.Fields.Add(bfOutgoingServer);
dtlview.Fields.Add(bfIncomingServer);
dtlview.Fields.Add(chkfIsDefault);
dtlview.DataBind();
//Events handling for detailsview
dtlview.ItemInserting += dtlview_ItemInserting;
dtlview.ItemInserted += dtlview_ItemInserted;
dtlview.ModeChanging += dtlview_ModeChanging;
//Add controls to place holder
PlaceHolder2.Controls.Add(dtlview);
}
protected void dtlview_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
e.Values["UserID"] = GetCurrentUserID();
}
protected void dtlview_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
}
protected void dtlview_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
dtlview.ChangeMode(e.NewMode);
if (e.NewMode != DetailsViewMode.Insert)
{
dtlview.DataSource = eds;
dtlview.DataBind();
}
}
}
I think what you have to do is add :
OnContextCreating="XXXXDatasource_OnContextCreating"
OnContextDisposing="XXXXDatasource_OnContextDisposing"
To your EntityDataSource.
Then in you code :
protected void XXXXDatasource_OnContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
e.Context = DBEntities.Entities;
}
protected void XXXXDatasource_OnContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e)
{
e.Cancel = true;
}
That way, your ObjectContext is correctly set to the EntityDataSource used by your DetailsView.
At least that's what I read as best practice (also look up one object context per page request)

how to use FileSystemWatcher using asp.net(C#)

SENARIO: i have few folders on my FTP server, belongs to particular user. Suppose i have 10GB total space and i assign 1GB to each user i.e can accomodate 10 users having 1GB each.
now users can add/delete/edit any type of file to utilize the storage space. All i need to do is to restrict users not to exceed 1gb space for their file storage. For this i want to use FileSystemWatcher to notify me that a user had created/deleted/edited a file so that i can minimize the space from 1gb incase of creation of a file or add a space incase of deletion.
this is the piece of coding using FSW. when user gets loged-in with proper id and password, respective folder is opened (present at FTP server) where he can add/delete/edit any type of file and according to that i hav to monitor d space ulitilized by him.
but d problem is the event handlers (written in console). i dont understand what happens when this code is being runned... i dontknow how to use FSW class so that i can monitor d changes user is making in his folder.
please help ... THANX
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class _Default: System.Web.UI.Page {
public class ClsFileSystemWatcher {
public static void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnDeleted(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnCreated(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnRenamed(object source, RenamedEventArgs e) {
Console.WriteLine("File "+e.OldFullPath+" [Changed to] "+e.FullPath);
}
public static void OnError(object source, ErrorEventArgs e) {
Console.WriteLine("Error "+e);
}
public void FileWatcher(string InputDir) {
using (FileSystemWatcher fsw = new FileSystemWatcher()) {
fsw.Path = InputDir;
fsw.Filter = #"*";
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName|NotifyFilters.Attributes|NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.Security|NotifyFilters.Size|NotifyFilters.CreationTime|NotifyFilters.DirectoryName;
fsw.Changed += OnChanged;
fsw.Created += OnCreated;
fsw.Deleted += OnDeleted;
fsw.Renamed += OnRenamed;
fsw.Error += OnError;
fsw.EnableRaisingEvents = true;
//string strOldFile = InputDir + "OldFile.txt";
//string strNewFile = InputDir + "CreatedFile.txt";
//// Making changes in existing file
//using (FileStream stream = File.Open(strOldFile, FileMode.Append))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Appending new line in Old File");
// sw.Flush();
// sw.Close();
//}
//// Writing new file on FileSystem
//using (FileStream stream = File.Create(strNewFile))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Writing First line into the File");
// sw.Flush();
// sw.Close();
//}
//File.Delete(strOldFile);
//File.Delete(strNewFile);
// Minimum time given to event handler to track new events raised by the filesystem.
Thread.Sleep(1000);
}
}
}
private DAL conn;
private string connection;
private string id = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\project\\Desktop\\BE prj\\dbsan.mdb;Persist Security Info=False";
conn = new DAL(connection);
////*** Opening Respective Folder of a User ***////
DirectoryInfo directories = new DirectoryInfo(#"C:\\Inetpub\\ftproot\\san\\");
DirectoryInfo[] folderList = directories.GetDirectories();
if (Request.QueryString["id"] != null) {
id = Request.QueryString["id"];
}
string path = Path.Combine(#"C:\\Inetpub\\ftproot\\san\\", id);
int folder_count = folderList.Length;
for (int j = 0; j < folder_count; j++) {
if (Convert.ToString(folderList[j]) == id) {
Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
}
}
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(path);
}
}
Each time you reload the page you create new FSW - in that case you won't get any events raised, because from the point of newly created FSW nothing was changes. Try to preserve your FileSystemWatcher object in the Session state.
So flow would look like:
User logs in – you create FSW and preserve it in Session
User reloads the page – get FSW from Session (do not create new one)
You should create a worker role (service) for this type of thing. I think it is not appropriate to have something like this inside of a page.

Resources