Tuesday, February 28, 2012

How to Read XML String and Create XML File in Asp.net

SqlCommand cmd = new SqlCommand("Select top 10 * from TblAppointment", con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        XmlDocument doc = new XmlDocument();

        foreach (var XML in ds.Tables[0].AsEnumerable())
        {
            doc.LoadXml(XML.Field<string>("AppointmentTransXml"));

            doc.Save(Server.MapPath("XML") + "//" + XML.Field<string>("Patientname") + ".xml");
        }

Tuesday, February 14, 2012

XML in LINQ ( Get Values from XML Using LINQ )

public
{
WeatherData GetCityTemprature(
string city)XElement xe = XElement.Load(@".\WeatherForecast\City.xml");

var query = from xElem in xe.Elements("City")
where xElem.Element("Name").Value == city

select new WeatherData{
City = (
string)xElem.Element("Name"),
State = (
string)xElem.Element("State"),
MaxTemprature = Convert.ToDouble(xElem.Element(
"MaxTemp").Value),
MinTemprature = Convert.ToDouble(xElem.Element(
"MinTemp").Value),
};

}

WeatherData wd = query.First();
return wd;

Tuesday, January 24, 2012

Simple Error Log Creator


1. Add This as Common in Your Application.

public static void WriteError(string errorMessage)
{
try
{
string path = "~/LogFile/" + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}


2. ErrorLog is as Class Name. (Example --> Below)


How to Convert XML String to XML and Get Values With LINQ


XDocument XMLdoc = XDocument.Parse(XMLString);
try
{
string body;
string CcMailid = "";
string Path = Server.MapPath("~/Imgs/Logo.gif");
string rootUrl = Page.Request.ServerVariables["HTTP_HOST"].ToString() + RequestDetails;

var XMLVales = (from _Doc in XMLdoc.Descendants("Product")
select new
{
ProductName = _Doc.Element("ProductName").Value,
Quantity = _Doc.Element("ProductQuanity").Value,
Amount = _Doc.Element("ProductAmt").Value,
TotalAmount = _Doc.Element("ProductTotalAmt").Value
}).Last();

body = ObjHtmlBody.BodyContentNew(RequesterName, SubmitterName, ReqId, XMLVales.ProductName, XMLVales.Quantity, XMLVales.Amount, XMLVales.TotalAmount, rootUrl);
string[] _ReqCode = ddlRequestFrom.SelectedValue.Split('^');
if (Convert.ToString(Session["EmpCode"]) != Convert.ToString(_ReqCode[0]))
{
CcMailid = _ReqCode[1].Trim();
}
ObjSendMail.SendEmail(ToMailId, CcMailid, "New Requst", body, Path);
}
catch (Exception Ex)
{
ErrorLog.WriteError("FrmRequest() --> : buildAndSendEmail() : --> " + Ex);
}

Friday, January 6, 2012

How to check IN Clause Condition in LINQ


List<int> ObjCircleList = null;
ObjCircleList = new List<int>();

for (int i = 0; i < ddlCircle.SelectedValue.Split(',').Count(); i++)
{
ObjCircleList.Add(Convert.ToInt32(ddlCircle.SelectedValue.Split(',')[i]));
}

string CentreNames = "", CentreIds = "";

foreach (Center c in Dbi.Contactss.ListContacts(db, 10).Where(p => ObjCircleList.Contains(p.CorpCenterId)).OrderBy(p => p.Center_name))
{

CentreNames = CentreNames + c.Center_name.Trim().TrimEnd() + "|";
CentreIds = CentreIds + c.id.ToString() + "|";
}

Tuesday, December 6, 2011

How to Convert PdfBinary to PDF

In Html Page
<table width="100%">
<tr>
<td align="right">
</td>
</tr>
<tr>
<td>
<iframe id="ipdfviewer" width="100%" height="400px" runat="server"></iframe>
</td>
</tr>
</table>

In Cs Page

void ShowPdf()
{
Con.Open();
string Qry = "Select * from TblLabTempReport";
SqlCommand Cmd = new SqlCommand(Qry, Con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(Cmd);
da.Fill(ds);

string FileName;
byte[] byteArray;

if (ds != null && ds.Tables[0].Rows.Count > 0)
{
string LocationPath = "PdfContent/";
string WriteFilePath = Server.MapPath("~/PdfContent/");

byteArray = (byte[])ds.Tables[0].Rows[0]["PdfBinary"];
FileName = "Sample.pdf";
LocationPath = LocationPath + FileName;
WriteFilePath = WriteFilePath + FileName;
if (!File.Exists(WriteFilePath))
{
System.IO.File.WriteAllBytes(WriteFilePath, byteArray);
}
ipdfviewer.Attributes.Add("src", LocationPath);
}
Con.Close();
}

Command Parameters Declaration

Type 1
Con.Open();
string Qry = "Update tblcentreselection set ImgHeaderBinayByte=@ImgBinary,ImgExtension=@ImgExtention where Centreid=@CenterId";
SqlCommand cmd = new SqlCommand(Qry, Con);
cmd.Parameters.Add("@ImgBinary", SqlDbType.VarBinary);
cmd.Parameters["@ImgBinary"].Value = ImgBinary;
cmd.Parameters.Add("@ImgExtention", SqlDbType.VarChar);
cmd.Parameters["@ImgExtention"].Value = StrExtension;
cmd.Parameters.Add("@CenterId", SqlDbType.Int);
cmd.Parameters["@CenterId"].Value = Convert.ToString(Session["_SelCen"]);
cmd.ExecuteNonQuery();
Con.Close();
Type 2
Con.Open();
string Qry = "Update tblcentreselection set ImgHeaderBinayByte=@ImgBinary,ImgExtension=@ImgExtention where Centreid=@CenterId";
SqlCommand cmd = new SqlCommand(Qry, Con);
Cmd.Parameters.AddWithValue("", OrgId);
Cmd.Parameters.AddWithValue("", ExVisitId);
Cmd.Parameters.AddWithValue("", ReportType);
Cmd.Parameters.AddWithValue("", LabPdfBinary);
cmd.ExecuteNonQuery();
Con.Close();