Wednesday, December 26, 2012

A potentially dangerous Request. Form value was detected from the client (MVC3) How to Solve

A potentially dangerous Request. Form value was detected from the client (MVC3) How to Solve
Add this in Global.asax.cs
protected void Application_Start()
{
      GlobalFilters.Filters.Add(new ValidateInputAttribute(false));
}

Add this in Web.config Under <system.web>

<httpRuntime  requestValidationMode="2.0" />

<pages validateRequest="false">

See Sample Image


 

Friday, November 23, 2012

How to Remove Filter and Soring in dataTable

Remove Sorting and Filter in dataTable

$(document).ready(function () {
        $('#TblAgent').dataTable({ "bSort": false, "bFilter": false});
});

Initial sorting diable

$(document).ready( function() {
  $('#TblAgent').dataTable({
    "aaSorting": []
});
})

Monday, August 27, 2012

Simple SQL Cursor for Reference

SELECT * FROM #tmpTab;           
                DECLARE @x nvarchar(400)
                DECLARE cursorName CURSOR
                FOR Select Kju FROM #tmpTab
                                OPEN cursorName
                                FETCH NEXT FROM cursorName INTO @x
                                WHILE @@FETCH_STATUS = 0
                                                BEGIN
                                                EXEC sp_executesql @x
                                                PRINT @x
                                                FETCH NEXT FROM cursorName
                                                INTO @x
                                                END
                                CLOSE cursorName
                                DEALLOCATE cursorName

Export to Excel from DataTable without using Grid



public void ExportToExcel(DataTable dt)
{
 if (dt.Rows.Count > 0)
 {
 string filename = "DownloadMobileNoExcel.xls";
 System.IO.StringWriter tw = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
 DataGrid dgGrid = new DataGrid();
 dgGrid.DataSource = dt;
 dgGrid.DataBind();
 //Get the HTML for the control.
 dgGrid.RenderControl(hw);
 //Write the HTML back to the browser.
 //Response.ContentType = application/vnd.ms-excel;
 Response.ContentType = "application/vnd.ms-excel";
 Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
 this.EnableViewState = false;
 Response.Write(tw.ToString());
 Response.End();
 }
}

Saturday, August 18, 2012

Simple Merge Stored Procedure with Function


Merge and Where in with String Values

Create proc [dbo].[LT_MergeRoleDetails]
(
@ID int,
@ValueId int,
@SelectedPermission varchar(max)
)
as
BEGIN
MERGE RoleDetail AS TARGET Using

(SELECT @ID,@ValueId) as NEW (ID,ValueId) ON
(
TARGET.ID=NEW.ID AND
TARGET.ValueId=NEW.ValueId
)

WHEN MATCHED THEN
UPDATE SET
TARGET.ID=NEW.ID,             
TARGET.ValueId=NEW.ValueId,
TARGET.UpdatedOn=GETDATE(),
TARGET.Obsolete=0
WHEN
NOT MATCHED BY TARGET THEN
INSERT (ID,ValueId,CreatedOn,UpdatedOn,Obsolete)
VALUES (NEW.ID,NEW.ValueId,GETDATE(),GETDATE(),0);

-- Update
Update RoleDetail set Obsolete=1 where cast(RoleDetId as varchar) not in (SELECT * FROM UF_CSVToTable(@SelectedPermission)) and ValueId=@ValueId
END
Function
Create FUNCTION [dbo].[UF_CSVToTable]
(
 @psCSString VARCHAR(8000)
)
RETURNS @otTemp TABLE(sID VARCHAR(20))
AS
BEGIN
 DECLARE @sTemp VARCHAR(10)

 WHILE LEN(@psCSString) > 0
 BEGIN
  SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
                    LEN(@psCSString)))
  SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
                               LEN(@psCSString)) + 1, LEN(@psCSString))
  INSERT INTO @otTemp VALUES (@sTemp)
 END

RETURN
END

How to Create Log File in Asp.Net 2010

1)  Add This in AssemblyInfo
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

2) Add This in web.Config

<configuration>

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
 
  <log4net debug="true">
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="LogFile\\Log.txt"/>
  <appendToFile value="true"/>
  <rollingStyle value="Size"/>
  <maxSizeRollBackups value="10"/>
  <maximumFileSize value="2KB"/>
  <staticLogFileName value="true"/>
  <layout type="log4net.Layout.PatternLayout">
 <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n"/>
  </layout>
 </appender>
 <root>
    <level value="DEBUG"/>
    <appender-ref ref="RollingLogFileAppender"/>
 </root>
 </log4net>

</configuration>

3) Create one folder Called LogFile

4) Add this Page where you want to catch the Log

private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

5) Use log4net dll

Tuesday, August 14, 2012

How to Call WCF Class file to Asp.net Application

How to call WCF Class file to Asp.net Application with out creating Class file in Asp.net Application
OssWebService.Service1Client ObjOssWeb = new OssWebService.Service1Client();
OssWebService.UserInfo ObjUserinfo = new OssWebService.UserInfo();


[DataContract]

public class UserInfo{
[
DataMember]
public string CenterName { get; set; }[
DataMember]
public string PatientId { get; set; }[
DataMember]
public string PatientName { get; set; }[
DataMember]
public string PhoneNo { get; set; }[
DataMember]
public string Age { get; set; }[
DataMember]
public List<StudyInfo> StudyInfo { get; set; }}

Thursday, August 9, 2012

How to get data from multiple datacontext (DBML) in Linq


var ObjPermission = dbOne.Permissions.ToList();

var ObjRoleMapping = (from RD in dbTwo.RoleDetails
join RM in dbTwo.RoleMasters on RD.RoleId equals RM.RoleID
                      where RM.RoleID == AgentId
                      select RD).ToList();

List<P> ObjResult = (from P in ObjPermission
join RML in ObjRoleMapping on P.PermissionID equals RML.PermissionId
              select P).ToList();

Multiple Table's Join In LINQ

List<PM> ObjPermission = (
from P in Permissions
join RD in RoleDetails on P.PermissionID equals RD.PermissionId
join RM in RoleMasters on RD.RoleId equals RM.RoleID
where RM.RoleID == AgentId
select P).ToList();

Thursday, June 7, 2012

Trim Empty Space Using JavaScript When doing Validation


function ValidateImage() {
   var fileName = document.getElementById('FUHeaderLogo').value;
   if (trim(fileName) == '') {
   alert("Please browse PNG Image");
   return false;
   }
   else {
   return true;
  }
}

function trim(s) {
    var l = 0; var r = s.length - 1;
    while (l < s.length && s[l] == ' ')
    { l++; }
    while (r > l && s[r] == ' ')
    { r -= 1; }
    return s.substring(l, r + 1);
 }


Monday, May 21, 2012

How to get Printable Contents and Non Printable Contents in Javascript



<script language="javascript" type="text/javascript">
function PopPrint() {
var originalContents = document.body.innerHTML;
var prtContent = document.getElementById('<%=Receipt.ClientID %>');
var printContents = prtContent.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>

Thursday, May 17, 2012

How to Get Filenames from Directory


DirectoryInfo di = new DirectoryInfo(@"E:\Empphoto\");
FileInfo[] files = di.GetFiles();
foreach (FileInfo f in files)
{
con.Open();
string Qry = "Insert into TblEmpPhoto(ImgNameWithExt,ImgName,ImgExt) Values (@ImgNameWithExt,@ImgName,@ImgExt);";
SqlCommand cmd = new SqlCommand(Qry, con);
cmd.Parameters.AddWithValue("@ImgNameWithExt", f.Name.ToString().ToUpper());
cmd.Parameters.AddWithValue("@ImgName", f.Name.Split('.')[0].ToString().ToUpper());
cmd.Parameters.AddWithValue("@ImgExt", f.Name.Split('.')[1].ToString().ToUpper());
cmd.ExecuteNonQuery();
con.Close();
}

Get FileName from Filepath




private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}



Wednesday, May 2, 2012

Linq IsNull for DateTime

var
result = from r in Dsdod.Tables[0].AsEnumerable()where r.IsNull("startdate") != true && r.IsNull("expirydate") != true && r.IsNull("category") != true && CurrentIST >= (r.Field<DateTime>("startdate")) && CurrentIST < (r.Field<DateTime>("expirydate"))select new { Id = r.Field<Int32>("adid"), PromoCode = r.Field<string>("category") };

Monday, April 23, 2012

How to Add Hyperlink in Girdview Hader Row in Asp.Net


protected void GrdScheduler_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int m = 1; m < e.Row.Cells.Count; m++)
{
HyperLink hlControl = new HyperLink();
hlControl.ForeColor = System.Drawing.Color.White;
hlControl.Text = e.Row.Cells[m].Text.Split('|')[0];
hlControl.NavigateUrl = "~/ToolTip/FrmCountDetails.aspx?Name=" + e.Row.Cells[m].Text.Split('|')[0] + "&Id=" + e.Row.Cells[m].Text.Split('|')[1] + "&Date=" + RDPFromDate.Text + "";
hlControl.Attributes.Add("OnClick", "var w=window.open(this.href, 'ViewCount', 'height=350, width=600,top=40,left=100,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=yes,status=no');w.focus(); return false;");
hlControl.ToolTip = "Click Here to view Details of " + e.Row.Cells[m].Text.Split('|')[0];
e.Row.Cells[m].Controls.Add(hlControl);
}
}
}
}

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;