How to edit an external web.config file? - winforms

I am trying to write a winform application that would be able to edit the web.config file of an installed web application.
I have read through the ConfigurationManager and WebConfigurationManager class methods but I am unsure as to how I can open the configuration file of a web app and edit it.
I am looking for a method that does not require me to load the config file as a regular XmlDocument, although I am willing to do that if that is the only option available.
Any advice would be appreciated.

Ok so here is the answer, I have the EXACT same scenario. I wanted to write a winforms app to allow normal users to update the web.config. You have to go about getting the config a goofy way...
// the key of the setting
string key = "MyKey";
// the new value you want to change the setting to
string value = "This is my New Value!";
// the path to the web.config
string path = #"C:\web.config";
// open your web.config, so far this is the ONLY way i've found to do this without it wanting a virtual directory or some nonsense
// even "OpenExeConfiguration" will not work
var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None);
// now that we have our config, grab the element out of the settings
var element = config.AppSettings.Settings[key];
// it may be null if its not there already
if (element == null)
{
// we'll handle it not being there by adding it with the new value
config.AppSettings.Settings.Add(key, value);
}
else
{
// note: if you wanted to you could inspect the current value via element.Value
// in this case, its already present, just update the value
element.Value = value;
}
// save the config, minimal is key here if you dont want huge web.config bloat
config.Save(ConfigurationSaveMode.Minimal, true);
Here is an example of what it does
Before:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="MyKey" value="OldValue" />
</appSettings>
<connectionStrings>
<add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
After:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="MyKey" value="This is my New Value!" />
</appSettings>
<connectionStrings>
<add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<trust level="Full" />
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
</system.web>
</configuration>
Just be careful, if you give it an invalid path, it will just create a config file at that path / filename. Basically, do a File.Exists check on it first
BTW, while you're at it, you could write a class that represents your settings in your web.config. Once you do this, write your getters/setters to read/write the settings in the web.config. Once THIS is done, you can add this class as a datasource and drag the databound controls onto your winform. This will give you a completely databound winform web.config editor that you can easily hammer out in a matter of minutes. I've got an example at work that I'll post tomorrow.
Fully featured winforms solution
So this is a relatively simple solution to writing a Gui to edit a web.config, some may say its overly complicated when notepad will do just fine but it works for me and my audience.
It basically works as described above, I wrote a class that had the configuration points that I wanted as properties. The ctor opens the file from a path and the getters / setters pull the data out of the returned configuration object, finally it has a save method that writes it out. With this class, I'm able to add the class as a datasource and drag / drop bound controls onto winforms. From there all you have to do is to wire up a button that calls the save method on your class.
Configuration class
using System.Configuration;
// This is a representation of our web.config, we can change the properties and call save to save them
public class WebConfigSettings
{
// This holds our configuration element so we dont have to reopen the file constantly
private Configuration config;
// given a path to a web.config, this ctor will init the class and open the config file so it can map the getters / setters to the values in the config
public WebConfigSettings(string path)
{
// open the config via a method that we wrote, since we'll be opening it in more than 1 location
this.config = this.OpenConfig(path);
}
// Read/Write property that maps to a web.config setting
public string MySetting
{
get { return this.Get("MySetting"); }
set { this.Set("MySetting", value); }
}
// Read/Write property that maps to a web.config setting
public string MySetting2
{
get { return this.Get("MySetting2"); }
set { this.Set("MySetting2", value); }
}
// helper method to get the value of a given key
private string Get(string key)
{
var element = config.AppSettings.Settings[key];
// it may be null if its not there already
if (element == null)
{
// we'll handle it not being there by adding it with the new value
config.AppSettings.Settings.Add(key, "");
// pull the element again so we can set it below
element = config.AppSettings.Settings[key];
}
return element.Value;
}
// helper method to set the value of a given key
private void Set(string key, string value)
{
// now that we have our config, grab the element out of the settings
var element = this.config.AppSettings.Settings[key];
// it may be null if its not there already
if (element == null)
{
// we'll handle it not being there by adding it with the new value
config.AppSettings.Settings.Add(key, value);
}
else
{
// in this case, its already present, just update the value
element.Value = value;
}
}
// Writes all the values to the config file
public void Save()
{
// save the config, minimal is key here if you dont want huge web.config bloat
this.config.Save(ConfigurationSaveMode.Minimal, true);
}
public void SaveAs(string newPath)
{
this.config.SaveAs(path, ConfigurationSaveMode.Minimal, true);
// due to some weird .net issue, you have to null the config out after you SaveAs it because next time you try to save, it will error
this.config = null;
this.config = this.OpenConfig(newPath);
}
// where the magic happens, we'll open the config here
protected Configuration OpenConfig(string path)
{
return ConfigurationManager.OpenMappedExeConfiguration(
new ExeConfigurationFileMap() { ExeConfigFilename = path },
ConfigurationUserLevel.None);
}
}
Build and then from there you can just goto your winform designer, goto Data > Show Data Sources (Shift+Alt+D). Right click > Add New Data Source and add it as an object as shown
Data Source Configuration Wizard 1 of 2 http://img109.imageshack.us/img109/8268/98868932.png
Data Source Configuration Wizard 2 of 2 http://img714.imageshack.us/img714/7287/91962513.png
Drag it (WebConfigSettings, the topmost) onto the winform. In my case, I will remove the navigator as that is for a List and I just have one.
Freshly added databound controls http://img96.imageshack.us/img96/8268/29648681.png
You should have something like webConfigSettingsBindingSource at the bottom of the designer (shown in the next pic). Goto the code view and change the ctor to this
public Form1()
{
InitializeComponent();
// wire up the actual source of data
this.webConfigSettingsBindingSource.DataSource = new WebConfigSettings(#"c:\web.config");
}
Add a save button to your winform
Save button added http://img402.imageshack.us/img402/8634/73975062.png
Add the following event handler
private void saveButton_Click(object sender, EventArgs e)
{
// get our WebConfigSettings object out of the datasource to do some save'n
var settings = (WebConfigSettings)this.webConfigSettingsBindingSource.DataSource;
// call save, this will write the changes to the file via the ConfigurationManager
settings.Save();
}
There, now you have a nice simple databound web.config editor. To add / remove fields, you just modify your WebConfigSettings class, refresh the datasource in the Data Sources window (after a build), and then drag n drop the new fields onto the UI.
You'll still have to wire up some code that specifies a web.config to open, for this example I just hard coded the path.
The cool thing here is all the value that a GUI adds. You can easily add directory or filebrowser dialogs, you can have connection string testers etc. All are very easy to add and very powerful to the end user.

I highly recommend you to use XElement along with LINQ enabled (LINQ to XML).
For instance you want to change the connectionString. This type of code is good enough
var connString = from c in webConfigXElement.appSettings.connectionString
where c.name == "myConnection"
select c;
and now you have full control over the <connectionString /> element, and do whatever you want to do with it.
I am referring you to MSDN for learning and also a Kick Start for instant working.
Hope this helps you to have full control over your .xml without pain.

Here you go, I wrote a toy app (VB.NET Windows client) that edits XML files using a Tree / Grid for navigating and editing.
You might get some ideas from it. The VS project file for it is here or just an MSI to install it is here, if you want to try it out on your web.config.
It loads the file into a DataSet (DataSet.ReadXML()) which parses it into DataTables, then displays and allows editing of the contents in a standard DataGrid. Then it will save the edited content back to the XML file (DataSet.WriteXML()).

All app.config and web.config are just XML files. You can open and edit them using XMLDocument, XMLWriter, etc.

Related

WPF native windows 10 toasts

Using .NET WPF and Windows 10, is there a way to push a local toast notification onto the action center using c#? I've only seen people making custom dialogs for that but there must be a way to do it through the os.
You can use a NotifyIcon from System.Windows.Forms namespace like this:
class Test
{
private readonly NotifyIcon _notifyIcon;
public Test()
{
_notifyIcon = new NotifyIcon();
// Extracts your app's icon and uses it as notify icon
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
// Hides the icon when the notification is closed
_notifyIcon.BalloonTipClosed += (s, e) => _notifyIcon.Visible = false;
}
public void ShowNotification()
{
_notifyIcon.Visible = true;
// Shows a notification with specified message and title
_notifyIcon.ShowBalloonTip(3000, "Title", "Message", ToolTipIcon.Info);
}
}
This should work since .NET Framework 1.1. Refer to this MSDN page for parameters of ShowBalloonTip.
As I found out, the first parameter of ShowBalloonTip (in my example that would be 3000 milliseconds) is generously ignored. Comments are appreciated ;)
I know this is an old post but I thought this might help someone that stumbles on this as I did when attempting to get Toast Notifications to work on Win 10.
This seems to be good outline to follow -
Send a local toast notification from desktop C# apps
I used that link along with this great blog post- Pop a Toast Notification in WPF using Win 10 APIs
to get my WPF app working on Win10. This is a much better solution vs the "old school" notify icon because you can add buttons to complete specific actions within your toasts even after the notification has entered the action center.
Note- the first link mentions "If you are using WiX" but it's really a requirement. You must create and install your Wix setup project before you Toasts will work. As the appUserModelId for your app needs to be registered first. The second link does not mention this unless you read my comments within it.
TIP- Once your app is installed you can verify the AppUserModelId by running this command on the run line shell:appsfolder . Make sure you are in the details view, next click View , Choose Details and ensure AppUserModeId is checked. Compare your AppUserModelId against other installed apps.
Here's a snipit of code that I used. One thing two note here, I did not install the "Notifications library" mentioned in step 7 of the first link because I prefer to use the raw XML.
private const String APP_ID = "YourCompanyName.YourAppName";
public static void CreateToast()
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("This is my title!!!!!!!!!!"));
stringElements[1].AppendChild(toastXml.CreateTextNode("This is my message!!!!!!!!!!!!"));
// Specify the absolute path to an image
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Your Path To File\Your Image Name.png";
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
imageElements[0].Attributes.GetNamedItem("src").NodeValue = filePath;
// Change default audio if desired - ref - https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-audio
XmlElement audio = toastXml.CreateElement("audio");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Reminder");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.IM");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Mail"); // sounds like default
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call7");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call2");
//audio.SetAttribute("loop", "false");
// Add the audio element
toastXml.DocumentElement.AppendChild(audio);
XmlElement actions = toastXml.CreateElement("actions");
toastXml.DocumentElement.AppendChild(actions);
// Create a simple button to display on the toast
XmlElement action = toastXml.CreateElement("action");
actions.AppendChild(action);
action.SetAttribute("content", "Show details");
action.SetAttribute("arguments", "viewdetails");
// Create the toast
ToastNotification toast = new ToastNotification(toastXml);
// Show the toast. Be sure to specify the AppUserModelId
// on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
}
UPDATE
This seems to be working fine on windows 10
https://msdn.microsoft.com/library/windows/apps/windows.ui.notifications.toastnotificationmanager.aspx
you will need to add these nugets
Install-Package WindowsAPICodePack-Core
Install-Package WindowsAPICodePack-Shell
Add reference to:
C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd
And
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
And use the following code:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
for (int i = 0; i < stringElements.Length; i++)
{
stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));
}
// Specify the absolute path to an image
string imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png");
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Toast Sample").Show(toast);
The original code can be found here: https://www.michaelcrump.net/pop-toast-notification-in-wpf/
I managed to gain access to the working API for windows 8 and 10 by referencing
Windows.winmd:
C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral
This exposes Windows.UI.Notifications.
You can have a look at this post for creating a COM server that is needed in order to have notifications persisted in the AC with Win32 apps https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/10/16/quickstart-handling-toast-activations-from-win32-apps-in-windows-10/.
A working sample can be found at https://github.com/WindowsNotifications/desktop-toasts

Silverlight: Business Application Needs Access To Files To Print and Move

I have the following requirement for a business application:
(All of this could be on local or server)
Allow user to select folder location
Show contents of folder
Print selected items from folder (*.pdf)
Display which files have been printed
Potentially move printed files to new location (sub-folder of printed)
How can I make this happen in Silverlight?
Kind regards,
ribald
First of all, all but the last item can be done (the way you expect). Due to security protocols, silverlight cannot access the user's drive and manipulate it. The closest you can get is accessing silverlight's application storage which will be of no help to you whatsoever in this case. I will highlight how to do the first 4 items.
Allow user to select folder location & Show contents of folder
public void OnSelectPDF(object sender)
{
//create the open file dialog
OpenFileDialog ofg = new OpenFileDialog();
//filter to show only pdf files
ofg.Filter = "PDF Files|*.pdf";
ofg.ShowDialog();
byte[] _import_file = new byte[0];
//once a file is selected proceed
if (!object.ReferenceEquals(ofg.File, null))
{
try
{
fs = ofg.File.OpenRead();
_import_file = new byte[fs.Length];
fs.Read(_import_file, 0, (int)fs.Length);
}
catch (Exception ex)
{
}
finally
{
if (!object.ReferenceEquals(fs, null))
fs.Close();
}
//do stuff with file - such as upload the file to the server
};
}
If you noticed, in my example, once the file is retrieved, i suggest uploading it to a webserver or somewhere with temporary public access. I would recommend doing this via a web service. E.g
//configure the system file (customn class)
TSystemFile objFile = new TNetworkFile().Initialize();
//get the file description from the Open File Dialog (ofg)
objFile.Description = ofg.File.Extension.Contains(".") ? ofg.File.Extension : "." + ofg.File.Extension;
objFile.FileData = _import_file;
objFile.FileName = ofg.File.Name;
//upload the file
MasterService.ToolingInterface.UploadTemporaryFileAsync(objFile);
Once this file is uploaded, on the async result, most likely returning the temporary file name and upload location, I would foward the call to some javascript method in the browser for it to use the generic "download.aspx?fileName=givenFileName" technique to force a download on the users system which would take care of both saving to a new location and printing. Which is what your are seeking.
Example of the javascript technique (remember to include System.Windows.Browser):
public void OnInvokeDownload(string _destination)
{
//call the browser method/jquery method
//(I use constants to centralize the names of the respective browser methods)
try
{
HtmlWindow window = HtmlPage.Window;
//where BM_INVOKE_DOWNLOAD is something like "invokeDownload"
window.Invoke(Constants.TBrowserMethods.BM_INVOKE_DOWNLOAD, new object[] { _destination});
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Ensure you have the javascript method existing either in an included javaScript file or in the same hosting page as your silverlight app. E.g:
function invokeDownload(_destination) {
//some fancy jquery or just the traditional document.location change here
//open a popup window to http://www.myurl.com/downloads/download.aspx? fileName=_destination
}
The code for download.aspx is outside the scope of my answer, as it varies per need and would just lengthen this post (A LOT MORE). But from what I've given, it will "work" for what you're looking for, but maybe not in exactly the way you expected. However, remember that this is primarily due to silverlight restrictions. What this approach does is rather than forcing you to need a pluging to view pdf files in your app, it allows the user computer to play it's part by using the existing adobe pdf reader. In silverlight, most printing, at least to my knowledge is done my using what you call and "ImageVisual" which is a UIElement. To print a pdf directly from silverlight, you need to either be viewing that PDF in a silverlight control, or ask a web service to render the PDF as an image and then place that image in a control. Only then could you print directly. I presented this approach as a lot more clean and direct approach.
One note - with the temp directory, i would recommend doing a clean up by some timespan of the files on the server side everytime a file is being added. Saves you the work of running some task periodically to check the folder and remove old files. ;)

app.Config file entries are cleared on Repair installed Setup

I have created a Setup Project for my Project. This project connects to a live DB server through asmx services. That URL will be determined after the client will deploy the web services on some server. So in setup project i have added a "TextBoxes" dialog in User Interface Editor section of the Setup Project where i have enabled only one TextBox to get the URL of the deployed Services. In my project i have added a file to be executed during Setup installation and i have defined it as follows:
[RunInstaller(true)]
public class InstallerHelper : System.Configuration.Install.Installer
{
// Other Code also exists that is not needed to be shown here<br/>
//.....
// The following method gets executed during setup installation
public override void Install(IDictionary stateSaver)
{
try
{
base.Install(stateSaver);
//Proceed only if the Context object has some parameters
if (Context.Parameters.Count != 0 && !string.IsNullOrEmpty(Context.Parameters["WEBSITEURL"]))
{
//Get the installation Folder's Path
string installationFolder = Context.Parameters["INSTALLFOLDER"];
// Get the Site's URL entered by Client
string websiteUrl = Context.Parameters["WEBSITEURL"];
//Create different Key Value pairs based on entered URL
string[][] keyValues = {
new string[] {"SiteUrl",websiteUrl},
new string[] {"WebServiceURL", websiteUrl + "Users.asmx" },
new string[] {"TicketsServiceURL", websiteUrl + "Tickets.asmx"},
new string[] {"CampaignsAndProjetcsServiceURL", websiteUrl + "CampaignsAndProjetcs.asmx"},
new string[] {"EntitiesURL", websiteUrl + "Entities.asmx"},
new string[] {"AccountsURL", websiteUrl + "Accounts.asmx"},
new string[] {"TransactionsURL", websiteUrl + "Transactions.asmx"},
new string[] {"RelatedReportsURL", websiteUrl + "RelatedReports.asmx"},
new string[] {"GiftAidsURL", websiteUrl + "GiftAids.asmx"}
};
// Load the app.Config file and store these values in it.
//********************************************
string configFilePath = installationFolder + #"\MyProject.exe.config";
XmlDocument configuration = new XmlDocument();
// Load App.Config File
configuration.Load(configFilePath);
//Add the values in it
Utility.UpdateValue(keyValues, configuration);
//Save configuration File
configuration.Save(configFilePath);
//********************************************<br/>
}
}
catch (Exception ex)
{
throw new InstallException("The following Error(s) occured during installation. \n " + ex.Message);
}
}
}
Here i Store the entered URL and some other generated URLs of different web services in App.Config of the Project to be used in Project for accessing data.
It works fine when i install a fresh copy of the Setup, but problem occurs when i try to Repair the installed project by again executing the Setup.exe file.
Repair process does not asks me to enter the URL again and also the Items stored in App.Config during first time installation are lost. So the whole application stops working.
Any help is greatly appreciated
A good approach is to save this custom information somewhere and retrieve it during maintenance using searches:
create some string registry entries which contain your custom properties; the registry entry value can be something like:
[WEBSITEURL]
create registry searches which read these entries and save them in your custom properties; for this use the property names for the actual searches
This way a repair will read the property values from registry and restore your original properties.
Both the Registry Editor and Launch Conditions Editor can be opened by selecting your setup project in Solution Explorer and clicking the appropriate button on its top pane.

From Silverlight, generate file to save on user's computer without hitting server

I have a Silverlight app where I want to do an export of some data. The file output format is most likely going to be PDF or Word. But let's assume I can generate the file contents appropriately. I want to be able to pop up a Save dialog for the user to save this data or open it directly in the program.
Now obviously I could just launch the user to a URL and do the export on the server, and change the MIME type of the response to be either Word or PDF. This would work just fine. However, the sticking point is that I already have the correct data on the client (including complex filters and the like) and recreating this data set on the server just to send it back to the client again seems silly if I can avoid it.
Is there any way to take an existing set of data in Silverlight and generate a Word or PDF file and get it onto the user's computer? I could also do it from JavaScript using browser interop from Silverlight. I don't want to use out-of-browser Silverlight.
You need to use the SaveFileDialog class. Note that due to Silverlight's security settings, the SaveFileDialog needs to be opened as the result of a user event (e.g., a button click).
The dialog can be configured (if you want) using properties such as DefaultExt or Filter before you display it using the ShowDialog() method.
The ShowDialog() method will return true if the user correctly specified a file and clicked OK. If this is the case, you can then call the SaveFileDialog.OpenFile() method to access this file and write your data to it.
Example:
private void Button_Click(object sender, EventArgs e)
{
SaveFileDialog saveDialog = new SaveFileDialog();
if (saveDialog.ShowDialog())
{
System.IO.Stream fileStream = textDialog.OpenFile();
System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
sw.Write("TODO: Generate the data you want to put in your file");
sw.Flush();
sw.Close();
}
}

silverlight 4, dynamically loading xap modules

I know that it is possible to load xap modules dynamically using Prism or MEF framework. However, I'd like not to use those frameworks; instead load my xap files manually. So, I created the following class (adapted from internet):
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
The above code works fine; I can load any xap the following way:
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
Now, I have a UserControl called InvoiceView in the Sales.xap project, so I would like to instantiate the class. In the current project (Main.xap) I added reference to Sales.xap project, however, since I load it manually I set "Copy Local = False". But when executed, the following code throws TypeLoadException:
Sales.InvoiceView view = new Sales.InvoiceView();
It seems the code can't find InvoiceView class. But I checked that XapLoader's initXap() method was successfully executed. So why the code can't find InvoiceView class? Can someone help me with this problem?
This is based on the asker's self-answer below, rather than the question.
If you delete a project/module the output DLLs/XAP files do hang around. If you click the "show all files" button you will see some these left-over output files in your clientbin, bin and obj folders of related projects.
You can delete them individually from the project, or, when in doubt, search for all BIN and OBJ (e.g. using desktop explorer) and delete all those folders. The BIN/CLIENTBIN/OBJ folders will be recreated when needed (this the job that the "clean" option in Visual Studio should have done!)
Hope this helps.
Ok, I found the cause. The above code works. After creating a new silverlight project (Sales.xap) I happened to compile my solution once. Then I deleted App class in the Sales.xap and renamed default MainPage class to SalesView. However, no matter how many times I compile my solution, Visual Studio's development web server was loading the first version of Sales.xap (where from?), so my code couldn't find SalesView. In my host Asp.Net project I set development server's port to a different port number, and the problem gone. So the problem was with Visual Studio's development server. Apparently it is keeping compiled xap files in some temporary folder, and doesn't always update those xap files when source code changed.
What I do to avoid such problems when executing freshly compiled Silverlight is clear the browser cache, chrome even has a clear silverlight cache ;)
this XAP Cache phenomena is often due to the visual studio embedded web server (ASP.NET Development Server).
Just stop the occurence of this server and the cache will be cleared.
Start again your project and the latest build of your xap is called.

Resources