I created a HttpModule and attached a AuthenticateRequest handler to check if token exists in querystring. There I remove token from querystring and redirect to the required page without token, starting a new request life cycle (https://msdn.microsoft.com/en-us/library/ms178473.aspx) and building the Session normaly using the cookie.


User request: example.com/example?token=12312kaasd12asd21ko323
AuthenticateRequest Handler authenticate user and redirect to example.com/example

public class TokenAuthenticationModule : IHttpModule
    public void Init(HttpApplication application)
        application.AuthenticateRequest += this.CheckToken;

    private void CheckToken(object sender, EventArgs e)
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;

        string token = context.Request.QueryString["token"];
        if (MyTokenClass.IsValid(token))
            int userCode = DecryptToken(token);
            User user = GetUserFromDataBase(userCode);
            FormsAuthentication.SetAuthCookie(user.UserName, false);

This works, but AuthenticateRequest fires for all folders that my page uses, css, images etc. I want to check if uri has a token parammeter just once per page.

I can't use events after AuthenticateRequest because after that the FormsAuthentication will override the uri redirectig to login example.com/login.aspx?ReturnUrl=example&token=12312kaasd12asd21ko323

I want to create o module between request and FormsAuthentication.

I can get redirectUrl after FormsAuthentication in the BasePage and redirects to the requested page, but this is a workaround that I'm trying to avoid.

Is it possible to create that module with this behaviour? How can I do it?

I'm using WebForms.


This question already has an answer here:

I'm struggling with some System.Data.SqlClient.SqlDataReader problems.

Actually, I made a DatabaseHandler for execute queries more convenient, with IDisposable interface for using statements.

When I use the handler for reading single article, query successfully executed, however, the handler disposed before I use data.

Then, the result is NullReferenceException. Here's the article reading code, and Dispose().

// Article Reading Code
using (var ArticleHandler = new DatabaseHandler())
    var ArticleReader = ArticleHandler.ExecuteCommand("ARTICLE_INQUIRY",
        new DatabaseParameter[]
            new DatabaseParameter("seq", Sequence)
        }) as System.Data.SqlClient.SqlDataReader; //Query Successful

    if (!ArticleReader.HasRows)
        ArticleReader.Read(); //Data Read Successful

        CurrentArticle.title = (string)ArticleReader["title"]; //NullReferenceException ?
        CurrentArticle.category = (string)ArticleReader["category"];
        CurrentArticle.datetime = (string)ArticleReader["written_datetime"];
        CurrentArticle.content = (string)ArticleReader["content"];

/* Database Handler Dispose() */
public void Dispose()
    CurrentConnection = null;

P.S. I checked column names, and they are match with database information.

When i upload file using AsyncFileUpload path view like image. File Path

If i try to edit or clear path in client side (in uploadComplete) make error. I try many tutorial but not help my, any help? note: my correct path not contain (fakepath word)

I'm working on a project that is ASP.NET with a C# code behind. Almost every code behind is empty. Everything is jquery/javascript with ajax calls to the WCF web services. I have been tasked to implement some cross scripting measures. I enabled page validation in the web config and encode all inputs, query strings etc. I cannot figure out how to prevent the the following:

Normal URL: https://localhost:3333/StartInfo.aspx

Failed URL: https://localhost:3333/StartInfo.aspx/%35%37%34%38%34

This fails the test because 57484 becomes rendered on the page. The project is made up of 3 pages that all use the same master page. Any help would be greatly appreciated.

I have created a PDF using crystal reports (I am using crystal reports for Visual studio 2015). On generated PDF, ItextObject named txtwebSite shows some link to external website. for example: ItextObject has value "http://www.google.com". This external website opens in the same explorer window. For opening this external link in new tab i do this:

right click ItextObject txtwebSite and choose -> format object -> select hyperlink Tab and select option: A website on Internet, then click formula button under hyperlink Information: In format Formula region I added this: '@txtwebSite'+'&sWindow=New'

But still It opens external web site in the same explorer window. I am not sure if the formula I added is correct or not? Please correct if somebody knows. OR some other way to do the same thing may be?

In my Asp.Net MVC project I have created a custom authorize attribute. If user is not authenticated my filter is working correctly. But when I in my login page and wrote a controller that is not exist I cannot redirect to custom error page.

This is my custom authorize attribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
        if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

Because of my default route my application is redirecting to Account/Index action

    public ActionResult Index(string returnUrl) { return View(); }

    public ActionResult Index2(string systemUserId, string returnUrl)


    [HttpPost, ValidateAntiForgeryToken, AllowAnonymous]
    public ActionResult Index(AccountViewModel accountModel,string returnUrl)


How can I skip my filter for custom error pages ?

cmd = new SqlCommand("SELECT column1,column2 from tablename");
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
ds = new DataSet();
using (MemoryStream stream=new MemoryStream())
  XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
  xmlWriter.WriteElementString("tagname1", ds.Tables[0].Rows[0]["column1"].ToString());
  xmlWriter.WriteElementString("tagname2", ds.Tables[0].Rows[0]["column2"].ToString());
//end table tag
//end tagname
//end document

byte[] byteArray = stream.ToArray();

                    Response.AppendHeader("Content-Disposition", "filename=invoice.xml");
                    Response.AppendHeader("Content-Length", byteArray.Length.ToString());
                    Response.ContentType = "application/octet-stream";

This is the code for export to xml file,when I tried to export into xml file at the browser end it gives only values of xml file not the xml tags. I need the xml tags along with the values as a final output. Thanks.

How can technologies like SQL Reporting services OR telerik report designer Helping developers to allow end users to design there custom report within the application ?

Edit : How end user of application can develop his custom reports ?

How to display google map with location marker where i can pass city from code. if anyone can give example using Asp.net Or HTML code that will be good.

I have an existing ASP.NET website with a login. The login procedure is not trivial, because of routing to different front ends on different servers based on which user logs in. There is also some communication/login going on to a classic ASP website.

Now I want to start to decouple the first step of the login procedure using a tiny Angular2 app. Basically this should just collect the user and password and leave the login validation etc. to the existing ASP.NET logic. So from my naive point of view, this is the same as filling out user and password on my existing ASP.NET page and clicking the submit button.

I know that I can make http requests using angular2 and have successfully done so calling SOAP based web services which are part of the login validation process.

I have the idea that I can somehow fake the http request which is executed when submitting the login form in the existing ASP.NET page. But as far as I understand it right now, even if I could make an http request to my login.aspx site the response I would get would sit in my Angular2 obervable as text whereas I would like to leave my Angular2 app and "simply use" that response.

I am not even sure what questions to ask ... but how do I do that?
What have I not considered?

Some options I have:

  • It would be possible to change parts of the existing ASP.NET page(s).
  • I think it would be OK to open a new browser tab in which the existing ASP.NET app would be displayed.

I send parameters for WebMethod with Ajax and receive um object. But, paramters lost zeros in WebMethod, i send "00001234", in backend paramenters is "1234"

Ajax Code:

 var content = {valueS: "00001234" };
            type: "GET",
            dataType: 'json',
            data: content,
            async: false,
            url: "myPage.aspx/GetData",
            contentType: "application/json; charset=utf-8",
            success: function (data) { OnSucess(data); },
            error:   function(data) { OnError(data); }

Webmethod Code:

    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
    public static string GetData(string valueS)

I am trying to build a custom server composite control in ASP.NET. This control will be composed of two Telerik controls and a simple HTML button. I also implement the IScriptControl interface in order to add client side interaction.

I have successfully added event listener for the simple HTML button 'click' event. The problem is that I want to add an event listener for the Telerik controls events, for example:


This is the simple click event listener inside the client component class:

CustomControls.GreenButton.prototype = {

    initialize: function () {

        CustomControls.GreenButton.callBaseMethod(this, 'initialize');

        this._onButtonClickHandler = Function.createDelegate($get(this._buttonID), this._onButtonClick);

        // Successfully listening to click event               
        $addHandler($get(this._buttonID), 'click', this._onButtonClick);

        // What event do I have to listen for?? ( e.g. onClientDropDownOpening --> does not work )
        $addHandler($get(this._telerikControlID), 'unknown_event_name', this._onClientDropDownOpening);

    _onButtonClick: function (e) {
        // Event handling

    _onClientDropDownOpening: function(e) {
        // Event handling

In conclusion

How can I add an event listener for the event raised by Telerik's OnClientDropDownOpening RadDropDownTree control method? Whith what name should I replace unknown_event_name ??

$addHandler($get(this._telerikControlID), 'unknown_event_name', this._onClientDropDownOpening);

I am attempting to SET CURRENT PACKAGESET before executing a DB2 Stored Procedure on a mainframe through vb.net.

I found the following link http://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.swg.im.dbclient.adonet.ref.doc/doc/DB2ConnectionClassConnectionStringProperty.html

which gives the property Keyword: CurrentPackageSet, Description: Issues the SET CURRENT PACKAGESET statement after every connection.

however I can not seem to access this property.

Dim myConnectionString As String Implements _ IDbConnection.ConnectionString
                myConnectionString = DB2Conn.ConnectionString
            Dim myConnection As New DB2Connection(myConnectionString)

            DB2StoredProc = New DB2Command(SchemaOwner & ".XXXX_WEB2OBJ", myConnection)
            DB2StoredProc.CommandType = Data.CommandType.StoredProcedure

I have attempted




but these don't appear to exist.

I have a project A that uses Razor rendering based on Sitecore 8. Meanwhile, there is a project B that uses XSLT rendering based on Sitecore 6.6.

Recently, project B is going to revamp but still keeping use of Sitecore 6.6 I am thinking should I take this chance to change the rendering method from XSLT to Razor?

I did some research and found there are two sites that do the comparision.



Yet, I could not understand which is better? Is it actually better to use Razor?

Hi Can I call a function into my view to get the description of ids in the foreach

My view

   @if (Model != null)
                int i = 1;
                foreach (var item in Model)
                <tr class="">
                    <td class="left">@{ new Fullname().getfullname(item.student_id.value).ToString(); }</td>
                    <td class="left"></td>
                    <td class="left">@CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.paid_month.Value).ToUpper()</td>
                    <td class="left">@item.monthly</td>
                    <td class="left">@item.transport</td>
                    <td class="left">@item.discount_details</td>
                    <td class="left">@item.total</td>

in Fullname class

public class Fullname
    private dbEntities db = new dbEntities();
    public string getfullname(int? id)
        var StudentSelect = db.student.Where(s => s.student_id == id)
            .Select(s => new
                FullName = s.lastname + " " + s.firstname

        return StudentSelect.FirstOrDefault().FullName;

I'm trying to get the student fullname from the @item.student_id in the Model

but nothing displayed


I have an Ajax.ActionLink which sends a request to server and gets a result from server. So in AjaxOption I just write name of success function.

OnSuccess = "SuccessDeleteFunction"

but based on result I want to change DOM element.To pass current DOM element in success function I used this code:

OnSuccess = "SuccessDeleteFunction(this)"

But How can I have Both at the same time.

function SuccessDeleteFunction(result, tag) {

        if (result.Success) {
            //    do sth

Here is my code:

@foreach (var item in Model)
                            <tr class="ContentRow">
                                    @Html.DisplayFor(modelItem => item.Name)
                                    @Html.DisplayFor(modelItem => item.Email)
                                    @Ajax.ActionLink(" ", "Delete", "Product", new { id = @item.Id }, new AjaxOptions() { Confirm = "Are you sure?", HttpMethod = "get", OnSuccess = "SuccessDeleteFunction" }, new { @class = "btn fa fa-trash text-danger fa-2x " })


I have menus and submenus in it respectively and I would like the submenus to remain open unless an another menu is clicked

Below is my code which copies files from one folder to another folder but what i need is while copying the files from TempFiles to TempFiles1 if there is a file with that name in TempFiles1 it should ask the user that does he wants to replace,if yes it should get copied else it should not get copied.How can i do this.

protected void Page_Load(object sender, EventArgs e)
            btn1_Click(btn1, null);
        protected void btn1_Click(object sender, EventArgs e)
            string sourcePath = Server.MapPath(".") + "\\TempFiles\\";
            string targetPath = Server.MapPath(".") + "\\TempFiles1\\";
            if (!Directory.Exists(targetPath))
            foreach (var srcPath in Directory.GetFiles(sourcePath))
                //Copy the file from sourcepath and place into mentioned target path, 
                //Overwrite the file if same file is exist in target path
                File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);

I'm using dotnet ef migrations add [abc] command add migration but it gives following error: No executable found matching command "dotnet-ef"

I have tried from command prompt as well as package manager console but gives same error. I have checked the path as well, i'm running command where my project.json sits.

Microsoft.EntityFrameworkCore.SqlServer is already installed.

project.json code is as follows:

  "version": "1.0.0-*",
  "dependencies": {
    "Bloomerang.Domain": "1.0.0-*",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1"
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
  "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview1-final",
    "imports": [

Can any one Guide me I ma newer how we Implement site Map in Asp.net MVC website Thanks in advance

I have creating pdf using itextsharp c#, for unicode hindi font used 'ARIALUNI.TTF', but when i create pdf, hindi font is not properly showing as input. So, how to get Hindi font in pdf properly. Can any other unicode font used for it? or any other resolution? Here is my code & html...

 private void fillgridview()
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("HindiName") });
        dt.Rows.Add("India", "भारत");
        dt.Rows.Add("China", "चीन");
        dt.Rows.Add("Australia", "ऑस्ट्रेलिया");
        dt.Rows.Add("United States", "अमेरिका");
        dt.Rows.Add("Canada", "कनाडा");
        dt.Rows.Add("Russia", "रूस");
        dt.Rows.Add("Itli", "इटली");
        dt.Rows.Add("France", "फ्रांस");
        GridView1.DataSource = dt;
    protected void btnExportPDF_Click(object sender, EventArgs e)
        GridView1.AllowPaging = false;
        BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);
        int[] widths = new int[GridView1.Columns.Count];
        for (int x = 0; x < GridView1.Columns.Count; x++)
            widths[x] = (int)GridView1.Columns[x].ItemStyle.Width.Value;
            string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
            //Set Font and Font Color
            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
            font.Color = BaseColor.WHITE;
            iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
            //Set Header Row BackGround Color
            cell.BackgroundColor = BaseColor.BLUE;
        for (int i = 0; i < GridView1.Rows.Count; i++)
            if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                for (int j = 0; j < GridView1.Columns.Count; j++)
                    string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);
                    //Set Font and Font Color
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    font.Color = BaseColor.BLACK;
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
                    //Set Color of row
                    if (i % 2 == 0)
                        //Set Row BackGround Color
                        cell.BackgroundColor = BaseColor.YELLOW;
        //Create the PDF Document
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        using (MemoryStream memoryStream = new MemoryStream())
        PdfWriter.GetInstance(pdfDoc, memoryStream);
        byte[] bytes = memoryStream.ToArray();        
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");

<asp:GridView ID="GridView1" runat="server" Width="300" HeaderStyle-BackColor="Blue"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="Yellow" AlternatingRowStyle-BackColor="White"
    RowStyle-ForeColor="Black" AutoGenerateColumns="false" Font-Names="Arial" Font-Size="12">
        <asp:BoundField ItemStyle-Width="200px" DataField="Name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="200px" DataField="HindiName" HeaderText="Hindi Name" />
<br />
<asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="btnExportPDF_Click" />

[<img src="~/AAA.jpg" width="300" height="100">][1]

  [1]: https://i.stack.imgur.com/xUpnG.jpg