I wrote a method to save an xml file from the web service. inside
that method first I check whether the file is exists.if exists,
delete it and save.if not save.
Other thing is I fire this methods using timer.(once a day automatically).
my question is when I save xml, if it exists what is happen.(Because when I run it locally visual studio asks "your xml has changed, do you want to reload it").does it reload automatically or completely delete the existing one or do we have to write a code to reload the xml file.
this is my code.
//method to save xml
public void sendValue()
{
string wbserviceUrl = "https://someurl.ashx";
WebClient clientOne = new WebClient();
string result = clientOne.DownloadString(wbserviceUrl);
XmlDocument cruisexmlDocument = new XmlDocument();
if (System.IO.File.Exists(#"D:/Anuprojects/Mppro/XmlFiles/Cruisedata/cruiseprodutsfour.xml"))
{
System.IO.File.Delete(#"D:/Anuprojects/Mppro/XmlFiles/Cruisedata/cruiseprodutsfour.xml");
cruisexmlDocument.LoadXml(result);
cruisexmlDocument.Save("D:/Anuprojects/Mppro/XmlFiles/Cruisedata/cruiseprodutsfour.xml");
}
else
{
cruisexmlDocument.LoadXml(result);
cruisexmlDocument.Save("D:/Anuprojects/Mppro/XmlFiles/Cruisedata/cruiseprodutsfour.xml");
}
}
//set daily time
public void setupTimer(TimeSpan savingTime)
{
DateTime current = DateTime.Now;
TimeSpan timeTogo = savingTime - current.TimeOfDay;
if(timeTogo < TimeSpan.Zero)
{
return;
}
this.timer = new Timer(x =>
{
this.sendValue();
},null,timeTogo,InfiniteTimeSpan);
}
//run it in the controller
public ActionResult Show()
{
setupTimer(new TimeSpan(11, 05,00));
return View();
}
If i understood your question, it is that if file already exist will it reload on execution?Answer to that would be that it depends on editor that you are using.
The reason why you are getting this error is like "the same file name is already exists in the directory.".Suggestion would be
Delete the exisitng file and save it [or]
Save the data with the date format like Products23102015.xml
Related
I am using the Gleamtech's DocumentUltimate Document Viewer in C# and want to get the cache folder name. which is created when a document is loaded.
Example : ~ App_Data\DocumentCache\~krcth
var cache = DocumentUltimateWebConfiguration.Current.GetCache();
string folder=cache.LocationId;
But it returns the same value every time and there is no folder for the same value. Is there any way I can get the newly created cache folder name?
Whole Code is down Below, I am trying to delete cache of a user when it exceeds 2 as multiple caches are slowing down the response.
DataTable docache = new DataTable();
if(Session["docache"] == null)
{
docache.Columns.Add("Path");
docache.Columns.Add("Time");
docache.Columns.Add("Number");
}
else
{
docache = (DataTable)Session["docache"];
}
var cache = DocumentUltimateWebConfiguration.Current.GetCache();
string path =cache.LocationId;
int cachecount = Convert.ToInt32(hfcache.Value.ToString());
cachecount++;
docache.Rows.Add(path, DateTime.Now.ToString("ddMMyyyyhhmmss"), cachecount);
hfcache.Value = Convert.ToString(cachecount);
if(docache.Rows.Count >2)
{
string deletecachepath=Server.MapPath("~/App_Data/DocumentCache/" + docache.Rows[0]["Path"].ToString());
DeleteDirectory(deletecachepath);
docache.Rows[0].Delete();
}
Session["docache"] = docache;
//End
Anyone Have any idea about this?
I am using Visual Studio 2017 with smo dll
and trying to remove a file from database files with the following procedure
public string RemoveFile(string fileName,string databaseName)
{
Server srv = new Server(servConn);
Database database = srv.Databases[databaseName];
if (database != null)
{
var file = LoadFiles(databaseName).Where(a => a.Name == fileName);
if (!file.Any())
{
SqlServerDisconnect();
return "File Doesn't Exist.kindly Enter Right File Name";
}
else
{
DataFile fileToRemove = file.FirstOrDefault();
database.FileGroups[fileToRemove.Parent.Name].Files.Remove(fileToRemove);
database.Alter();
return "File Removed Successfully";
}
}
}
I am not going to mention the code of servConn parameter and SqlServerDisconnect in order to abbreviate code that I have used in other places and I am sure that it works well.
When I remove a file that I take it's name from one of existing files' logical names
RemoveFile("File1",MyDataBase")
I get the message:
You cannot perform operation Remove on an object in state Existing.
How can I update the state of the file before removing it even though state field is read only and is my way in removing the file right?
You are using SMO however; For alternative way, If you can execute the SQL to do these operations. I would suggest to simply use TSQLs to remove file like :
ALTER DATABASE SchoolDb2012
REMOVE FILE schoolDataFile1;
GO
You can find detailed information here https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-file-and-filegroup-options?view=sql-server-2017
i updated my procedure to drop the file directly and not from it's file group
and the exception disappeared
public string RemoveFile(string fileName,string databaseName)
{
Server srv = new Server(servConn);
Database database = srv.Databases[databaseName];
if (database != null)
{
var file = LoadFiles(databaseName).Where(a => a.Name == fileName);
if (!file.Any())
{
SqlServerDisconnect();
return "File Doesn't Exist.kindly Enter Right File Name";
}
else
{
DataFile fileToRemove = file.FirstOrDefault();
fileToRemove.Drop();
database.Alter();
return "File Removed Successfully";
}
}
}
You can use SetState change the SmoObject status
e.g.
var removeColumn = target.Columns.OfType<Column>().Where(x => !source.Columns.Contains(x.Name)).ToList();
foreach (Column columItem in removeColumn)
{
//If you want remove this item just replace Remove to SetState
columItem.SetState(SqlSmoState.ToBeDropped);
//If I use Remove will got You cannot perform operation Remove on an object in state Existing
//target.Columns.Remove(columItem.Name);
}
I am trying to deserialize XML from SSIS DTSX files. I have found the XSD files which I think are needed, found here: https://msdn.microsoft.com/en-us/library/gg587628%28v=sql.105%29.aspx. I have used xsd2code plugin for VS to create objects from the XSDs.
The problem: I am able to deserialize into these objects, but almost no actual data gets pulled in from the DTSX files.
In the code below, I have placed a break point at the WriteLine() command in Parse_XML() and looked at the contents of the two ExecutableTypePackage objects (executables and exec). Both have the same contents:
The property ExecutableType gets set to "SSIS.Package.3"
The Property collection (List<ExecutableTypePackageProperty>) has one element; its Name property is set to "PackageFormatVersion" and Value property is set to "6".
That's all. While those values are correct, there's a lot more data in the file that's not getting pulled in. But I get no warnings nor exceptions.
Admittedly, I don't have much experience with XML, and using the serialization methods is very new to me, but I have used them for validating the XML structure of report files (RDL), and never ran across any such issues. I have been beating my head against the wall for 2 full days on this now, and I am not making any progress. I have searched every which way I can think of for answers on this, but I don't find anyone else having this problem.
string file = null;
public Form1()
{
InitializeComponent();
}
private void Run_btn_Click(object sender, EventArgs e)
{
Parse_XML();
MessageBox.Show("Done!");
}
private void Parse_XML()
{
TextReader tr = new StreamReader(file);
XmlSerializer serializer = new XmlSerializer(typeof(DTSX.ExecutableTypePackage));
DTSX.ExecutableTypePackage executables = (DTSX.ExecutableTypePackage)serializer.Deserialize(tr);
DTSX.ExecutableTypePackage exec = DTSX.ExecutableTypePackage.Deserialize(File.ReadAllText(file));
MessageBox.Show(String.Format("Found {0} executables in package.", exec.Executable.Count));
Console.WriteLine("Done loading root object.");
}
private void File_btn_Click(object sender, EventArgs e)
{
int text_size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
text_size = text.Length;
File_txtbx.Text = file;
}
catch (IOException)
{
}
}
Console.WriteLine(file);
Console.WriteLine(text_size);
Console.WriteLine(result);
}
I'm trying to save two Lists of objects in the phone ApplicationSettings, but I'm stuck at a strange issue (But it's probably me making a silly mistake somewhere).
If I only save one of the lists, it works as supposed - It'll save it, and reload it when app is launched next time.
But if I try to save 2 lists, none of them seem to be saved correctly. No errors or anything, just "blankness".
See code below.
//My save method
public void Gem()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains(INDTASTNINGER_LIST))
{
settings[INDTASTNINGER_LIST] = _indtastningsListe;
}
else
settings.Add(INDTASTNINGER_LIST, _indtastningsListe);
if (settings.Contains(INDTASTNINGER_LIST2))
{
settings[INDTASTNINGER_LIST2] = _indtastningsListe2;
}
else
settings.Add(INDTASTNINGER_LIST2, _indtastningsListe2);
settings.Save();
}
//Constructor supposed to load settings
public Indtastninger()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains(INDTASTNINGER_LIST))
{
_indtastningsListe = null;
_indtastningsListe = (List<Indtastning>)settings[INDTASTNINGER_LIST];
}
if (settings.Contains(INDTASTNINGER_LIST2))
{
_indtastningsListe2 = null;
_indtastningsListe2 = (List<Indtastning>)settings[INDTASTNINGER_LIST2];
}
}
What am I doing wrong?
If I comment out the part with "list2" stuff, the first one will be saved/retrieved perfectly.
I have faced the same issue some time ago, the problem is that you only can save on the IsolatedStorage objects that are XML serializables.
if you save other object, it will work even with the debugger but when the app is restarted, all the saved data is lost.
I have looked all over for this. It could be me just typing the wrong thing in search I'm not sure. So, if you know a good tutorial or example of this please share. I'm trying to learn.
I have a C# Windows Form app I'm working on. I have information (movies in this case) saved in an XML file. I saved the xml file like this.
//Now we add new movie.
XmlElement nodRoot = doc.DocumentElement;
string allMyChildren = nodRoot.InnerText;
string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(movieEditNameTextbox.Text);
int indexLookForNewMake = allMyChildren.IndexOf(capitalized);
if (indexLookForNewMake >= 0)
{
MessageBox.Show("Movie is already saved.", "Error");
}
else
{
XmlElement el = doc.CreateElement("Name");
el.InnerText = capitalized;
doc.DocumentElement.AppendChild(el);
//Check if Year is really a Number.
if (movieEditYearTextbox.Text.All(Char.IsDigit))
{
//Remove ' cause it gives errors.
string capitalizedFixed = capitalized.Replace("'", "");
string capitalizedFinalFixed = capitalizedFixed.Replace("\"", "");
//Assign Attribute to each New one.
el.SetAttribute("Name", capitalizedFinalFixed);
el.SetAttribute("Type", movieEditTypeDropdown.Text);
el.SetAttribute("Year", movieEditYearTextbox.Text);
//Reset all fields, they don't need data now.
movieEditNameTextbox.Text = "";
movieEditYearTextbox.Text = "";
movieEditTypeDropdown.SelectedIndex = -1;
removeMovieTextbox.Text = "";
doc.Save("movie.xml");
label4.Text = "Movie Has been Edited";
loadXml();
}
else
{
//Error out. Year not a Number
MessageBox.Show("Check movie year. Seems it isn't a number.", "Error");
}
}
That all works fine. Now what I'm trying to do is make it where you can choose a directory, and it search the directory and sub directories and get file names and save them into the XML file.
I used this to try to accomplish this. It does pull the list. But it doesn't save it. It don't save the new information.
I can't use LINQ as it cause a confliction for some reason with other code.
DirectoryInfo dirCustom = new DirectoryInfo(#"D:\Video");
FileInfo[] filCustom;
filCustom = dirCustom.GetFiles("*",SearchOption.AllDirectories);
//Open XML File.
XmlDocument doc = new XmlDocument();
doc.Load("movie.xml");
XmlElement el = doc.CreateElement("Name");
string fulCustoms = filCustom.ToString();
foreach (FileInfo filFile in filCustom)
{
string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(filFile.Name);
string capitalizedFixed = capitalized.Replace("\"", "");
el.SetAttribute("Name", capitalizedFixed);
el.SetAttribute("Type", "EDIT TYPE");
el.SetAttribute("Year", "EDIT YEAR");
richTextBox1.AppendText(capitalizedFixed + "\r\n");
}
doc.Save("movie.xml");
label4.Text = "Movie Has been Edited";
loadXml();
Now, the richTextBox does display the information correctly but it don't save it.
The loadXml() is just my noobish way to refresh the datagridview.
I'm completely lost and don't know where to turn to. I know my coding is probarely horrible, lol. I'm new to this. This is my first more complex application I have worked on.
I can't think of anymore information that would help you understand what I mean. I hope you do.
Thank you so much for your help.
Not sure exactly what your LoadXML() method does but my only piece of advise with your issue is to change the way you are implementing this functionality.
Create an object called Movie
public class Movie
{
public Movie() {}
public String Title { get; set; }
blah... blah...
}
Then create a MovieList
public class MovieList : List<Movie> { }
Then implement the following 2 methods inside the MovieList.
public static void Serialize(String path, MovieList movieList)
{
XmlSerializer serializer = new XmlSerializer(typeof(MovieList));
using (StreamWriter streamWriter = new StreamWriter(path))
{
serializer.Serialize(streamWriter, movieList);
}
}
public static MovieList Deserialize(String path)
{
XmlSerializer serializer = new XmlSerializer(typeof(MovieList));
using (StreamReader streamReader = new StreamReader(path))
{
return (MovieList) serializer.Deserialize(streamReader);
}
}
Thats it... You now have your object serialized and you can retrieve the data to populate through binding or whatever other methods you choose.