I'm using visual studio to do my first full release of an application, which is a simple WPF GUI to configure a locally saved JSON object, and a console application to run in the background, using data from that object to monitor a website. I published each project to a test folder (we'll say Publish/), where each application manifest now resides, along with an 'Application Files' folder containing another sub-folder for each project.
I got the applications to run just fine - the problem is the configuration file saves to one folder a few more levels into C:\Users\username\AppData\Local\Apps\2.0\ and the console application is attempting to read from a completely separate folder. Both projects write and read using GetCurrentDirectory() for the file path. Is there a way I'm missing to remedy this?
Code for retrieving JSON object
try
{
//Confirms file exists
if (File.Exists(Directory.GetCurrentDirectory().ToString() + filePath))
{
//Initialize json variable to a string, then deserialize it into an instance of RCDetails
var json = File.ReadAllText(Directory.GetCurrentDirectory().ToString() + filePath);
RCDetails parsedDetails = JsonConvert.DeserializeObject<RCDetails>(json);
//Return deserialized JSON
return parsedDetails;
}
else return null;
And code for writing json object
public void WriteToFile(RCDetails rcd)
{
//Serialize input instance of RCDetails class
string JSONresult = JsonConvert.SerializeObject(rcd, Formatting.Indented);
//Remove old JSON object
if (File.Exists(Directory.GetCurrentDirectory().ToString() + jsonFilePath))
File.Delete(Directory.GetCurrentDirectory().ToString() + jsonFilePath);
//Create new JSON object with updated details
File.WriteAllText(Directory.GetCurrentDirectory().ToString() + jsonFilePath, JSONresult);
}
Exact steps for publishing project:
With console app selected, click Build > Publish (console app name)
Browse to C:\Users\username\Downloads\Publish\
For installation, choose "From a CD-ROM or DVD-ROM"
Select "the application will not check for updates
Select finish, and repeat all steps with same file path for config WPF
Solution I wound up finding (feel free to let me know if this is a bad plan). I just plopped this into both apps.
string s = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\IntendedFolder";
if (!Directory.Exists(s))
Directory.CreateDirectory(s);
Directory.SetCurrentDirectory(s);
Related
I have a method that gets called when a button is pressed,
private List<Page> _pages = new List<Page>();
public void LoadKern(int requestedKern)
{
TextAsset pages = Resources.Load("kern" + requestedKern) as TextAsset;
JSONArray jsonPages = JSON.Parse(pages.text)["pages"].AsArray;
foreach (JSONNode page in jsonPages)
{
_pages.Add(new Page(page["image"], page["text"]));
}
ImageSpriteRenderer.sprite = Resources.Load<Sprite>(_pages[currentPage].image);
TextSpriteRenderer.sprite = Resources.Load<Sprite>(_pages[currentPage].text);
}
The code works perfect when running it in the simulator but whenever I deploy it to an android device or use the Untiy Remote 4 it no longer updates the sprites.
Whenever I remove this line and set the resource manually, it does update when the button is pressed.
_pages.Add(new Page(page["image"], page["text"]));
It seems very odd that it does work on a desktop but not on Android, is there something I am missing?
I think it difficult to put it in the comment, so I write it as an answer here.
The simplest approach to verify this a problem due to the Resource.Load<>, is to add below code:
TextAsset pages = Resources.Load("kern" + requestedKern) as TextAsset;
Debug.Load(pages + "are Loading"); // to see if it is really loaded successfully
Connect your device and open the adb log, filter the message with "are loading".
If you see pages are null, then it is clear that Resource.Load<> is the culprit.
If it is Resource.Load<> problem, you can consider using StreamingAssets:
Any files placed in a folder called StreamingAssets in a Unity project will be copied verbatim to a particular folder on the target machine. You can retrieve the folder using the Application.streamingAssetsPath property. It’s always best to use Application.streamingAssetsPath to get the location of the StreamingAssets folder, it will always point to the correct location on the platform where the application is running.
On Android, you should use:
path = "jar:file://" + Application.dataPath + "!/assets/";
I suspect that your loading the text assets is carried out at runtime, when you package the app, the text assets are not read, and it might be excluded from the project, as Unity considers this "not used". When you run the app on Android, it is natural that it fails.
Using StreamingAssets approach, you force Unity to copy the text assets "verbatim" which assures it is accessible at runtime!
I have created a addin application with which i'm creating a solution with some files programtically. I have to integrate this in another winforms application. So once the user clicks the button a new project is created with some inputs dynamically.
In the addin project the form contains a method(OnConnection) which gets called automatically. This creates the project at run-time. The application works fine.
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
createProjectsFromTemplates(_applicationObject);
}
public void createProjectsFromTemplates(DTE2 dte)
{
try
{
// Create a solution with two projects in it, based on project
// templates.
Solution2 soln = (Solution2)dte.Solution;
string csTemplatePath;
//string vbTemplatePath;
string csPrjPath = "\\\\#####.com\\###\\My Documents\\TestCreateProject";
//string vbPrjPath = "C:\\UserFiles\\user1\\addins\\MyVBProject";
// Get the project template path for a C# console project.
// Console Application is the template name that appears in
// the right pane. "CSharp" is the Language(vstemplate) as seen
// in the registry.
csTemplatePath = soln.GetProjectTemplate("WpfApplication.zip", "CSharp");
System.Windows.Forms.MessageBox.Show("C# template path: " + csTemplatePath);
// Get the project template path for a Visual Basic console
// project.
// "vbproj: is the DefaultProjectExtension as seen in the
// registry.
//vbTemplatePath = soln.GetProjectTemplate("ConsoleApplication.zip", "vbproj");
//System.Windows.Forms.MessageBox.Show("Visual Basic template path: " + vbTemplatePath);
// Create a new C# console project using the template obtained
// above.
soln.AddFromTemplate(csTemplatePath, csPrjPath, "NewWCFCSharpAutoGeneratorProject", false);
// Create a new Visual Basic console project using the template
// obtained above.
//soln.AddFromTemplate(vbTemplatePath, vbPrjPath, "New VB Console Project", false);
Project prj;
ProjectItem prjItem;
String itemPath;
// Point to the first project (the Visual Basic project).
prj = soln.Projects.Item(1);
prjItem = prj.ProjectItems.AddFromFileCopy("\\\\####.com\\###\\My Documents\\SampelCSharp.cs");
// Retrieve the path to the class template.
//itemPath = soln.GetProjectItemTemplate("MyClass.zip", "CSharp");
//Create a new project item based on the template, in this
// case, a Class.
//prjItem = prj.ProjectItems.AddFromTemplate(itemPath, "MyNewClass.cs");
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show("ERROR: " + ex.Message);
}
}
Now i have to use the add in project from another application(Winforms) in order to create the project at run-time. I have build the addin project and imported the .dll file to that application. I have created an instance for the class and got the "OnConnection" method.But i'm not sure about what to be passed as the parameters. Because when debugging the method it shows the "application" parameter carries some "COM" objects within it.
Also if the application runs once, the new project is created when executed again it says file already exists in the path. I have to overwrite the older one.
What is the solution for this?
Note: Using Visual studio 2012 and Framework 3.5
Try this:
EnvDTE80.DTE2 dte2;
dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");
Connect objConnect = new Connect();
Array objArray = null;
objConnect.OnConnection(dte2, ext_ConnectMode.ext_cm_UISetup, null, ref objArray);
I have a VS2012 in C# solution with 4 projects in 4 layer structure(Presentation, BusinessLogic, DomainModel, DataAccess) and wanted to give the user the option to select the database's file's path at the Login form, which is in the Presentation layer (it is then used when a creating connection to the Database in a static method in the DataAccess layer). And the path would be saved and used the next time the application runs.
A bit more workflow example would be:
User starts the application and the login form appears;
User chooses the Database's file path with a FolderBrowserDialog or
OpenDirectoryDialog;
User works on the application then ends it;
User starts the application and the Database's file path is the one
he picked before;
User works on the application then ends it;
User starts the application and picks another file;
User works on the application then ends it;
User starts the application and the Database's file path is the one
he picked before.
Codewise I don't want to go passing along that string (path) all around my code for each method that needs to create a connection and such.
So any ideas on how to directly save it in the method that's directly using it? If not only when the user wants to change it then just forcing the user to pick the file when the starts the application.
Currently what I'm doing is forcing the user to put the file he wants in the solution's directory with a specific name before starting the application when he wants to use another Database file. For that I'm using:
public static string path;
public static OleDbConnection createConnection()
{
path = DirProject() + "\\Calibrações Equipamentos ULSM.accdb";
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
builder["Provider"] = "Microsoft.ACE.OLEDB.12.0";
builder["Data Source"] = path;
return new OleDbConnection(builder.ConnectionString);
}
private static string DirProject()
{
string DirDebug = System.IO.Directory.GetCurrentDirectory();
string DirProject = DirDebug;
for (int counter_slash = 0; counter_slash < 3; counter_slash++)
{
DirProject = DirProject.Substring(0, DirProject.LastIndexOf(#"\"));
}
return DirProject;
}
Configuration (=data) is not saved into a method (=code). It's usually saved into a configuration file. You can leverage .NET's application and user settings mechanism to achieve what you want.
Use User Settings
How To: Write User Settings at Run Time with C#
How To: Read Settings at Run Time With C#
I have to save images to a folder located in "c:\inetpub\wwwroot\" and named as "UploadedImages". Here is my code:
public string SaveImage(string base64,int compno)
{
string res = "";
try
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save(Server.MapPath("~/UploadedImages/ID"+compno+".jpg"));
}
}
res = "done";
}
catch (Exception ex) {
res = ex.ToString();
}
return res;
}
but it throws "A generic error occured in GDI+ at System.Drawing.Image.Save" exception. What am I doing wrong? This code works fine when saving image locally as
bm2.Save("D:Embasy\UploadedImages\ID"+compno+".jpg"));
What changes do I need to make to save images in localhost directory?
Your not going to believe this -- the site running v1.1 had a virtual directory set-up which was mapped to the directory in which the image was saved to -- things worked fine.
The v2.0 site also had the same virtual directory name, but the physical path was different -- I changed the path to point to the same directory as the v1.0 site and now the code works.
So in short -- you were right about the "path must exist".
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.
and kindly refer this link
http://msdn.microsoft.com/en-us/library/xs6ftd89.aspx
When you are using Server.Mappath
bm2.Save(Server.MapPath("~/UploadedImages/ID"+compno+".jpg"));
"~(tield)" : is point to project/application root folder c:\inetpub\wwwroot\yourproject
then find remaining your path /UploadedImages and then create ID1.jpg.
But your imagefolder "UploadImages" is exist in d: not in c:\inetpub\wwwroot\yourproject
if you want to exist your image folder in D: then you should to create
virtual directory and then you need to apply path as relevant
My problem actually was that every time i published website, I replaced the "UploadedImages" folder too and thus permissions were changed. So, i didnt replaced the folder again after changing its permissions and creating "everyone" group and giving full rights to it. Now code is working perfectly :)
I have a c# program which open *.postfix file.
If a user runs a (.lnk)shortcut which points to my type of file, my program will open the target.
So, how could my program know it is started by a (.lnk)shortcut (and get it's file path)?
In some circumstances,i need to replace the .lnk file.
Thanks!
Edited
First, thanks to guys who answered my question.
By following #Anders answer, i find out my problem lays here.
I made some changes to windows registry, so browser knows to throw customized protocol string to certain program.
some thing like this..
[InternetShortcut]
URL=myProtocol://abcdefg.....
That's maybe why i lost lpTitle. :(
I'm going to try this way:
Whenever my program invoked, of course fed with %1, program checks current opened explorer(Window), and try to get it's current path with IWebBrowserApp. With that path and desktop of course, scan and analyze *.lnk to determine which one to replace.
I think this will probably work, but not be sure. I will try.
continued
In native code you can call GetStartupInfo, if the STARTF_TITLEISLINKNAME bit is set in STARTUPINFO.dwFlags then the path to the .lnk is in STARTUPINFO.lpTitle. I don't know if there is a .NET way to get this info, you probably have to P/Invoke...
You don't. There's no way to do it. End of story.
So this has been brought to my attention due to a recent downvote. There's an accepted answer showing an idea that gets the path to the launching shortcut most of the time. However my answer is to the whole. OP wants the link to the shortcut so he can change it. That is what can't be done most of the time.
Most likely case is the shortcut file exists in the start menu but is unwritable. However other cases involve the shortcut coming from another launching application that didn't even read it from a disk but from a database (I've seen a lot of corporate level restricted application launch tools). I also have a program that launches programs from shortcuts not via IShellLink but by parsing the .lnk file (because it must not start COM for reasons) and launching the program contained. It doesn't pass STARTF_TITLEISLINKNAME because it's passing an actual title.
If you're using Visual Studio Setup Project to build an installer and do the file type association, you should follow these instructions http://www.dreamincode.net/forums/topic/58005-file-associations-in-visual-studio/
Open up your solution in Visual studio.
Add a Setup Project to your solution by file , add project,New project, Setup & Deployment projects,Setup project
Right-click on your setup project in the "Solution Explorer" window,Select view,then select file types.
you'll see the "file types" window displayed in Visual studio.At the top of the window will be "File types on target machine"
Right-click on "File types on target machine".the menu will pop up with Add "file type" Click on this.
you'll see "New document Type#1" added,and "&open"underneath it.
The "new document type#1" can be anything you want - change it to something descriptive.although the user never sees this,never use something common- be as unique as possible,Because you can overlay current file associations without even realizing it.For example,you might think"pngfile" might be a useful name- but using that will now send all"*.png" files to your application,instead of to an image viewer.A good practice maybe "YourCompantName.Filetype",where your company name is your name of your company's name, and "Filetype" is a descriptive text of your file.
In the "properties" window for your new type,you will need to change a few properties.:
Command:Change to the application that you want to run.If you click on the "..." and you will proberly want to locate and use the "primary Output..." File
Description: This is the description of the file type(if it doesn't describe it's self"
Extensions:This your list of extensions for you chosen Program.Separate each one with a ","
Icon:This will associate the icon with your file type,This shows up in the window explorer.
Now we move to that "&open ".This is an action that is available if your right-click on the file.The default action("&Open" is currently set as the default) is what happens when you double click on the file.Right click on your "New document type#1" to add actions,but for the moment,lets define our "&open" action
Click on "&Open".You will see in the properties window "Name","Arguments","Verbs". Verb is hidden from the user,but is the key that is stored in the registry.Leave it same as the name,But without the "&".The default for"Arguments" is "%1",Which means to pass the full path and filename to your application.You can add other stuff here as well,if you need to pass flags to your application to do special stuff.All this infomaton is getting passed to your application on the command line,so you'll need to be familiar with the "Environment.CommandLine" object.
If you need to set a different action as your default,just right click on the action and "set as default"
Basically, you'll pass the file path as an argument to your program. Then if it's a console application or Windows Forms , you should check the arguments in Program.Main
static void Main(string[] args)
{
//if file association done with Arguments %1 as per forum post above
//you file path should be in args[0]
string filePath = null;
if(args != null && args.Length > 0)
filePath = args[0];
}
For a WPF application you'll need to handle that in the StartUp event for your Application
void App_Startup(object sender, StartupEventArgs e)
{
string filePath = null;
if ((e.Args != null) && (e.Args.Length > 0))
{
filePath = e.Args[0];
}
}