In VS Installer Project, Commit() is not working properly - wpf

Using the Visual Studio Installer Project, I included the initial setup project in Install and Commit in Custom Actions that will perform the downloading of the cabinet file under the Windows\Temp\Target Folder folder. Consequently, the zip file will be unzipped.
I used async/await for the first time in DownloadCatalog(), but the zip file wasn't properly downloaded, even though the directory was created. I assumed the installing process stopped the downloading process. I then changed it.
I created the installation file without async. Then I ran it, but the result was the same. This code works fine when running it in an independent project. Do you have any suggestions?
namespace IntialSetupApp
{
[RunInstaller(true)]
public partial class IntialInstallApp : System.Configuration.Install.Installer
{
private readonly string temp = #"C:\Windows\Temp\Target Folder\";
private readonly string zipUrl = #"https://thank.you/so.much";
private readonly string catalog = #"C:\Windows\Temp\Target Folder\whateverXML.xml";
public IntialInstallApp()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
Directory.CreateDirectory(temp);
DownloadCatalog();
}
private Task DownloadCatalog()
{
try
{
string fileName = Path.Combine(temp, "ZippedCab.cab");
Uri uri = new Uri(url);
using (WebClient client = new WebClient())
{
client.DownloadFile(uri, fileName);
}
UnzipFile(fileName);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return Task.FromResult(true);
}
private Task UnzipFile(string filePath)
{
try
{
CabInfo cab = new CabInfo(filePath);
cab.Unpack(temp);
return Task.FromResult(true);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return Task.FromResult(false);
}
}
}
+Update
With the above code, I created the console project independently, and it created the folder and completed downloading the file. Therefore, it seems that installer prevents modifying other folders. Is there any workaround way?

The reason was The request was aborted: Could not create SSL/TLS secure channel., so I updated the code with this. Then it works fine.

Related

Best practices for file system of application data JavaFX

I am trying to build an inventory management system and have recently asked a question about how to be able to store images in a package within my src file. I was told that you should not store images where class files are stored but have not been told what the best practices are for file systems. I have created a new page that allows the user to input all the data about a new part that they are adding to the system and upload an image associated with the part. When they save, everything worked fine until you try to reload the parts database. If you 'refresh' eclipse and then update the database, everything was fine because you could see the image pop into the package when refreshed. (All database info was updated properly as well.
I was told not to store these types of 'new' images with the program files but to create a separate file system to store these types of images. Is there a best practice for these types of file systems? My confusion is when the program gets saved where ever it is going to be saved, I can't have it point to an absolute path because it might not be saved on a C drive or K drive and I wouldn't want an images folder just sitting on the C drive that has all of the parts images for anyone to mess with. Please give me some good resources on how to build these file systems. I would like the images folder 'packaged' with the program when I compile it and package all the files together, I have not been able to find any good information on this, thanks!
To answer this question, probably not in the best way, but works pretty well.
I ended up making another menuItem and menu that you can see at the top 'Image Management', where it lets the user set the location that they would like to save all the images as well as a location to back up the images. it creates the directory if it is not there or it will save over the images if the directory is already there. This menu will only appear if the user has admin privileges. I would think that this could be set up with an install wizard, but I have no idea how to make one, where it only runs on installation. I am also going to add an autosave feature to save to both locations if a backup location has been set. This is the best way I can think of managing all the parts images, if anyone has some good input, please let me know. I considered a server, but think that is too much for this application and retrieving images every time the tableView populates would take a lot of time. If interested the code I used is:
public class ImageDirectoryController implements Initializable{
#FXML private AnchorPane imageDirectory;
#FXML private Label imageDirLbl, backupLbl;
#FXML private Button setLocationButton, backupButton;
#FXML private TextField imageDirPathTxtField;
Stage window;
String image_directory;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
public void setImageDirectory(String image_address, String backup_address) {
imageDirLbl.setText(image_address);
backupLbl.setText(backup_address);
}
#FXML
public void setLocationButtonClicked () {
String imagesPath = imageDirPathTxtField.getText() + "tolmarImages\\";
File files = new File(imagesPath + "asepticImages");
File generalFiles = new File(imagesPath + "generalImages");
File facilitiesFiles = new File(imagesPath + "facilitiesImages");
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to set this location?");
if(answer) {
if (!files.exists()) {
if (files.mkdirs() && generalFiles.mkdirs() && facilitiesFiles.mkdirs()) {
JOptionPane.showMessageDialog (null, "New Image directories have been created!", "Image directory created", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog (null, "Failed to create multiple directories!", "Image directory not created", JOptionPane.INFORMATION_MESSAGE);
}
}
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = ?";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, imageDirPathTxtField.getText());
myStmt.setInt(2, 1);
myStmt.executeUpdate();
myStmt.close();
imageDirPathTxtField.clear();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#FXML
public void backupButtonClicked () {
String backupStatus = null;
if (backupLbl.getText().equals("")&& !imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!backupLbl.getText().equals("")){
backupStatus = backupLbl.getText();
} else {
JOptionPane.showMessageDialog(null, "You must create a directory.", "No directory created", JOptionPane.INFORMATION_MESSAGE);
return;
}
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to backup the images?");
if(answer) {
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = 2";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, backupStatus);
myStmt.executeUpdate();
myStmt.close();
String source = imageDirLbl.getText() + "tolmarImages";
File srcDir = new File(source);
String destination = backupStatus + "tolmarImages";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
JOptionPane.showMessageDialog(null, "Images copied successfully.", "Images copied", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Nancy fails to find static content in custom convention

I've set up a Nancy bootstrapper to serve static content from a non-default directory path (it's self hosted Nancy).
Strangely, the following works for the custom View location convention but not either of the js or css static content conventions (and yes, both files and folders exist at these locations!). My attempts at trying to resolve this are further compounded as I haven't figured out how to log errors which occur when static content is not found.
using System;
using System.IO;
using Nancy;
using Nancy.Conventions;
using Nancy.Bootstrapper;
using Nancy.TinyIoc;
namespace MyApp
{
public class ApplicationBootstrapper : DefaultNancyBootstrapper
{
private const string RELATIVE_PATH_TO_SOURCE = #"../static/MyApp/";
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("js", string.Concat(RELATIVE_PATH_TO_SOURCE, "Scripts/")));
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("css", string.Concat(RELATIVE_PATH_TO_SOURCE, "Content/")));
this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
{
return string.Concat(RELATIVE_PATH_TO_SOURCE, "Views/", viewName);
});
this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
{
return string.Concat(RELATIVE_PATH_TO_SOURCE, "Views/", context.ModuleName, "/", viewName);
});
base.ConfigureConventions(nancyConventions);
}
protected override IRootPathProvider RootPathProvider
{
get
{
return new MyRootPathProvider();
}
}
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
pipelines.OnError += (ctx, ex) =>
{
Console.WriteLine("RootPath : {0}", DebugRootPathProvider.RootPath);
Console.WriteLine("Unhandled error on request: {0} : {1}", ctx.Request.Url, ex.Message); //HACK
Console.WriteLine(ex.StackTrace); //HACK poor man's logging
return null;
};
}
}
public class MyRootPathProvider : IRootPathProvider
{
public static readonly string RootPath;
static MyRootPathProvider()
{
RootPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
public string GetRootPath()
{
return RootPath;
}
}
}
The output from Chrome and ProcMon is as follows:
How should I:
Log errors occurring with not found js and css files?
Resolve the 404 errors with the static file conventions?
Instead of logging you can use sysinternals process monitor and look for what files the nancy process (exe or IIS worker process) are attempting to read.
I had problems with serving static files (in my case js files) in a self host environment as well. They were not recognized at all, not even in the default "Content" folder. My solution: I installed the Microsoft StaticFiles NuGet Package.
In the startup class, register a static files folder like this:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseStaticFiles("/Scripts");
app.MapSignalR();
app.UseNancy();
}
}
This way, all files and subfolders in the "Scripts" folder are served as static files. There is also an overload of the UseStaticFiles() function that lets you map a physical path to a virtual path.
Important here: the call to UseNancy() has to be the very last, otherwise everything after it won't work. I also tried to combine it with SignalR, as you can see above, and there the UseNancy() call had to be at the end as well.

Create .db file in SD-CARD after checking its existence in blackberry?

I am working to create a db file in my application. Now I want to create the .db file on application installation just one time.
When I open the app, it just check for the existence of the file.
How can we check for a .db file in sdcard and if it exists before installation than to delete the file.
You can check if file exists or not using following code
FileConnection fileConnection = (FileConnection)Connector.open("file:///SDCard/foldername/" + "databasename.db");
boolean result=fileConnection.exists();
if(result)
{
//database available
}else{
//database not available
}
and next you want to check this when application first time instalation using
CodeModuleListener listner=new CodeModuleListener() {
public void modulesDeleted(String[] moduleNames) {
// TODO Auto-generated method stub
}
public void modulesAdded(int[] handles) {
// TODO Auto-generated method stub
//here you can check if database available or not if available then delete
try{
URI myURI = URI.create("file:///SDCard/foldername/" + "database_name.db");
DatabaseFactory.delete(myURI);
}catch (Exception e) {
// TODO: handle exception
}
}
public void moduleDeletionsPending(String[] moduleNames) {
// TODO Auto-generated method stub
}
};
CodeModuleManager.addListener(this.getApplication(), listner);

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.

Silverlight communication with XML RPC console server

I want to comunicate with Console XML RPC server from my silvelight application. Is it possibile?
Steps:
1. Start the Console XML RPC server
Code for Console XML RPC server is this:
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using CookComputing.XmlRpc;
public class StateNameServer : MarshalByRefObject, IStateName
{
public string GetStateName(int stateNumber)
{
return "whatever";
}
}
class _
{
static void Main(string[] args)
{
IDictionary props = new Hashtable();
props["name"] = "MyHttpChannel";
props["port"] = 5678;
HttpChannel channel = new HttpChannel(props,null,new XmlRpcServerFormatterSinkProvider());
ChannelServices.RegisterChannel(channel,false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(StateNameServer),"statename.rem",WellKnownObjectMode.Singleton);
Console.WriteLine("Press <ENTER> to shutdown");
Console.ReadLine();
}
}
Run Silverlight application
I used the code from http://code.google.com/p/xmlrpc-silverlight/
I created new Silverlight application to which I have attached the code from that link. When I start web site (in localhost with port 1139) which executes my SL app happens SecurityException.
void ResponseResponse(IAsyncResult result)
{
XmlRpcHelperRequestState state = result.AsyncState as XmlRpcHelperRequestState;
try
{
state.Response = (HttpWebResponse)state.Request.EndGetResponse(result);
...
}
catch (Exception e)
{
// comes here with SecurityException
}
finally
{
...
}
}
I am using VS2008 Professional,XP Professional, .net 3.5, Silverlight3. I will gladly provide any additional information (or code) which is needed.
I suspect that this is a case of a missing clientaccesspolicy.xml file.
Since your silverlight app will have been launched from another authority it will attempt to access this file the http://localhost:5678/. Since you little test doesn't support that file Silverlight blocks this cross "domain" activity.

Resources