How to make XMLTextWriter and XMLWriterSettings work together - asp.net

I have this code for the settings:
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.OmitXmlDeclaration = True
settings.NewLineOnAttributes = True
Then I have this code for the writer:
Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)
Please can you tell me how I make the settings apply to the writer?
Thanks a lot,
Phil.
EDIT: Code sample
Sub writexml_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Try
'Vars
Dim securityid As String = Input_securityid.Text
Dim enc As Encoding
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.OmitXmlDeclaration = True
settings.NewLineOnAttributes = True
settings.Encoding = enc
'Declare the writer and set file name / settings
Dim xml As XmlWriter = XmlWriter.Create(Server.MapPath("output.xml"), settings)
'start document
xml.WriteStartDocument()
xml.WriteComment("")
'start envelope
xml.WriteStartElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/")
'start body
xml.WriteStartElement("soap", "Body", Nothing)
xml.WriteAttributeString("xmlns", "ns1", Nothing, "http://its/foo.wsdl")
'start biographical capture
xml.WriteStartElement("ns1:biographicalcaptureElement")
'start securityid
xml.WriteStartElement("ns1:securityid")
xml.WriteValue(securityid)
'end securityid
xml.WriteEndElement()
'start requestdata
xml.WriteStartElement("ns1:requestdata")
'end requestdata
xml.WriteEndElement()
'end biographical capture
xml.WriteEndElement()
'end body
xml.WriteEndElement()
'end envelope
xml.WriteEndElement()
'end document
xml.WriteEndDocument()
'clean up
xml.Flush()
xml.Close()
Catch ex As Exception
errorlbl.Text = ex.ToString
Finally
errorlbl.Text = ("Created file ok")
End Try
End Sub
It does work fine if I use;
Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)
the xml is produced but settings are not applied.

This won't get you an XmlTextWriter, but to be honest I've always used XmlWriter when writing to a file anyway (XmlWriter is the base class of XmlTextWriter.)
You can use XmlWriter.Create(Server.MapPath("output.xml"), settings) which will give you an XmlWriter instead of an XmlTextWriter. Your encoding will then need to be set in your settings instance (settings.Encoding = enc.)
EDIT:
The sample code provided for me produces:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:ns1="http://its/foo.wsdl" />
</soap:Envelope>
EDIT 2:
Your namespace is causing a problem because it's trying to put the element name as ns1:securityid when it should be the element name is securityid and the namespace ns1. You'll need to separate these like you've done in the WriteAttributeString call, like so:
instead of: xml.WriteStartElement("ns1:biographicalcaptureElement")
use: xml.WriteStartElement("biographicalcaptureElement", "ns1")
With these changes in place I now get:
<!---->
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:ns1="http://its/foo.wsdl">
<biographicalcaptureElement xmlns="ns1">
<securityid>TEST123</securityid>
<requestdata />
</biographicalcaptureElement>
</soap:Body>
</soap:Envelope>

public partial class XMLWriter : System.Web.UI.Page
{
static string strFileName=#"E:\vijay112.xml";
static XmlTextWriter write = null;
public static int i = 0;
////// static string ProcessName=Process.GetCurrentProcess().ProcessName;
//////static Process[] processes = Process.GetProcessesByName(ProcessName);
////// if ( // {
////// // Application.ExitThread();
////// // }
public XMLWriter()
{
}
~XMLWriter()
{
//write.Close(); ;
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
write = new XmlTextWriter(strFileName, null);
div_div.InnerText = i.ToString();
}
catch (Exception ex)
{
}
}
public static string XMLWrite()
{
try
{
if (i == 0)
return "success";
else
{
return "please end the"+i+"more child";
}
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
try
{
}
catch ( Exception ex){}
}
}
public static void SetRootElement(string strRootElement)
{
write.WriteStartElement(strRootElement);
}
//public static void SetAttributeString(string strRootElement)
//{
// write.WriteString();
//}
public static void SetChildElement(string strChildElement)
{
write.WriteStartElement(strChildElement);
}
public static void SetAttribute(string strAttribute, string strValue)
{
write.WriteAttributeString(strAttribute, strValue);
}
public static void EndChildElement()
{
write.WriteEndElement();
}
public static void EndRootElement()
{
write.WriteFullEndElement();
}
protected void Bt_root_Click(object sender, EventArgs e)
{
SetRootElement(TB_key.Text);
}
protected void bt_child_Click(object sender, EventArgs e)
{
++i;
SetChildElement(TB_key.Text);
}
protected void BT_attribute_Click(object sender, EventArgs e)
{
SetAttribute(TB_key.Text, TB_value.Text);
}
protected void bt_endChild_Click(object sender, EventArgs e)
{
--i;
EndChildElement();
}
protected void bt_endroot_Click(object sender, EventArgs e)
{
EndRootElement();
}
protected void bt_xml_Click(object sender, EventArgs e)
{
write.Close();
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(#"E:\vijay\SourceCodeBackEnd\PrimeroWebService\Images\vijay112.xml");
// write.Flush();
Txml.Text= xmldoc.InnerXml;
}
protected void Txml_TextChanged(object sender, EventArgs e)
{
}
protected void bt_close_Click(object sender, EventArgs e)
{
}
}

Related

how to stop my FileSystemWatcher in start/stop button

I have a FileSystemWatchers monitoring 1 location in a Start/stop Button, but I canĀ“t manage to stop it, the button works pretty much well as when I click on it, it reads the code when it is off (the text changes to "start Watching") but it does not manage to stop monitoring, also I have tried "watcher.EnableRaisingEvents = false;" but it does not work could you please help me??
using System
using System.ComponentModel
using System.Diagnostics
using System.Drawing
using System.IO
using System.Windows.Forms
namespace Watcher
{
public partial class Form1 : Form
{
private bool isWatching
bool on = true
bool togglelight = true
Timer t = new Timer()
public Form1()
{
InitializeComponent()
}
private void button1_Click(object sender, EventArgs e)
{
if (isWatching)
{
stopWatching()
}
else
{
startWatching()
}
}
private void startWatching()
{
isWatching = true
button1.Text = "Stop Watching"
t.Start()
on = false;
var watcher = new FileSystemWatcher(#"C:\location1")
watcher.NotifyFilter = NotifyFilters.CreationTime
| NotifyFilters.CreationTime
| NotifyFilters.FileName
watcher.Changed += OnChanged
watcher.Error += OnError
watcher.Filter = "*.xlsx"
watcher.IncludeSubdirectories = false
watcher.EnableRaisingEvents = true
private void stopWatching()
{
isWatching = false;
button1.Text = "Start Watching"
button1.BackColor = Color.Gray
t.Enabled = false
t.Stop()
on = true
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return
}
Console.WriteLine(DateTime.Now + " tipo de cambio: " +
e.ChangeType + ". " + e.FullPath)
kNime_Bat(#" C:\Users\BAT\Knime_eSTORE.bat")
Console.WriteLine(DateTime.Now + " se proceso correctamente")
}
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException())
private static void PrintException(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}")
Console.WriteLine("Stacktrace:")
Console.WriteLine(ex.StackTrace)
Console.WriteLine()
PrintException(ex.InnerException)
}
}
private static void kNime_Bat(string ruta_del_archivoBat_knime)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo()
psi.UseShellExecute = false
psi.CreateNoWindow = true
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = ruta_del_archivoBat_knime
Process.Start(psi)
}
catch (Win32Exception)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Start Watching"
t.Interval = 1000
t.Tick += new EventHandler(t_Tick)
}
private void t_Tick(object sender, EventArgs e)
{
if (togglelight)
{
button1.BackColor = Color.DarkBlue
togglelight = false
}
else
{
button1.BackColor = Color.Gray
togglelight = true
}
}
}
}
I have tried watcher.EnableRaisingEvents = false in Stopwatching event but it seems like if it works in a new instance as it does not stop the watcher, how I know? because after I click on "stop" I make a new change in the watched folder and I get an answer in OnChanged event.

Using CefBrowser.ExecuteScriptAsync with BindObjectAsync Not Working

I am using the below code to try to bind a c# class that has been registered but do not see "dwgData" anywhere under Scope when debugging the webpage. What would dwgData be bound to?
private void ChromiumBrowserForm_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
ChromiumWebBrowser browser = new ChromiumWebBrowser("http://localhost:3000");
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.JavascriptObjectRepository.Register("dwgData", new DwgData(), true, null);
browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
browser.LoadingStateChanged += Browser_LoadingStateChanged;
}
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (e.IsLoading == false)
{
await Task.Run(() => browser.ExecuteScriptAsync("CefSharp.BindObjectAsync(\"dwgData\");"));
}
}
private void Browser_IsBrowserInitializedChanged(object sender, EventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (browser.IsBrowserInitialized)
{
browser.ShowDevTools();
}
}
public class DwgData
{
public void showMessage()
{
MessageBox.Show("HELLO FROM JS");
}
}

user control properties

i have a detail view with below markup and data source of this detail view is from stored procedure "spDocResult" like below:
select DocId,TransId,FileId,Filename,ContentType,Data,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where (DocId=#Docid)AND(Transid=#Transid)
one field of this detail view should be show Efile Names so i have made 1 user control for that
public partial class FileTemp : System.Web.UI.UserControl
{
private EDMSDataContext _DataContext;
private IEnumerable<tblFile> _Efiles;
public IEnumerable<tblFile> Efiles
{
set { _Efiles = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Download")
{
_DataContext = new EDMSDataContext();
//you can get your command argument values as follows
string FileId = e.CommandArgument.ToString();
int _FileId = Convert.ToInt32(FileId);
tblFile Efile = (from ef in _DataContext.tblFiles
where ef.FileId == _FileId
select ef).Single();
if (Efile != null)
{
download(Efile);
}}}
private void download ( tblFile Efile)
{
Byte[] bytes = (Byte[])Efile.Data.ToArray();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = Efile.ContentType.ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ Efile.FileName.ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
public override void DataBind()
{
base.DataBind();
GridViewEfile.DataSource = _Efiles;
GridViewEfile.DataBind();
}
}
now i have problem because datasource of detailview comes from a stored procedure and properties of user control is from tblFile, so when i use DetailsView1_DataBound i do not know how i have to get user control properties.when i use below code, i have error
can not implicity convert type string to system.collection.generic.iEnumerable<tblfile>
i have error for this line
fileList.Efiles = docresult.Filename;
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
spDocResultResult docresult = (spDocResultResult)DetailsView1.DataItem;
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
fileList.DataBind();
}
This might not be a data binding issue at all. It's a little hard to gather from the context, but...
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
Is fileList.Efiles a list of items that you just want to assign a file name to? If so, you might just need to foreach through them.
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
Also, add this line to your Efiles declaration to solve the Get accessor error.
public IEnumerable<tblFile> Efiles
{
get { return _Efiles; } // <- here
set { _Efiles = value; }
}

Passing DataKeys between pages

Using a GridView on the default page and want to show details of the row selected on another page. The code for capturing and sending the datakey is -
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
Response.Redirect("InvoicePage.aspx? EntityID= " + GridView1.DataKeys[index].Value.ToString());
}
And the code for retrieving the value is -
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["EntityID"];
}
My problem is that the id variable is a null on the receiving page. What am I missing?
Your URL should look something like this: InvoicePage.aspx?EntityID=", No space before or after EntityID
By The way Remove the white space : aspx?<>*EntityID<>*=
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
string id = GridView1.DataKeys[index].Value.ToString();
Response.Redirect("InvoicePage.aspx?EntityID="+id);
}
Try to add :
private string _EntityId;
//To check if value pass on query string
//but this is not really required if you want
public string EntityId
{
get
{
if (Request.QueryString["EntityID"] != null)
{
try
{
_EntityId = Convert.ToString(Request.QueryString["EntityID"].ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
_EntityId="0";
}
return _EntityId;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Request.QueryString["EntityID"].ToString();
string id = EntityId;
}
Regads

User Control events

I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}
you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}

Resources