I'm unable to retrieve a list of events using the Facebook Graph API. When performing a GET using the below call, no data is returned. It says the app doesn't have user_events permissions when using the Graph Explorer. I receive that same error message after I grant the user_events app permission using the "Configure App Center Permissions," then perform re-oauth, and test using the new token received. How do you grant the app the user_events permission?

https://graph.facebook.com/v2.5/me/events?access_token=TOKEN

enter image description here

Good evening,

I wrote a small code in c# that reads files from harddrive and outputs that info to a webpage using asp.net.

Information about those files is being changed in codebehind.

I managed to have variables read and displayed on webpage, but they change only after refresh, when I used setTimeout it would always read the same variable leaving me thinking that codebehind does not get reexecuted.

How would it be possible to have them updated live without need to refresh the entire page?

Thanks in advance!

I'm downloading an Excel file (dynamically created in a Winforms app and saved to a database) in a Web API project using this method:

[Route("api/deliveryperformance/{unit}/{begindate}/{enddate}")]
public HttpResponseMessage Get(string unit, string begindate, string enddate)
{
    // adapted the first part of this code from http://stackoverflow.com/questions/11176066/how-do-i-insert-retrieve-excel-files-to-varbinarymax-column-in-sql-server-2008
    byte[] excelContents;

    string selectStmt = "SELECT BinaryData FROM ReportsGenerated WHERE FileBaseName = @fileBaseName";
    string fbn = string.Format("deliveryperformance/{0}/{1}/{2}", unit, begindate, enddate);
    using (SqlConnection connection = new SqlConnection(ProActWebReportsConstsAndUtils.CPSConnStr))
    using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection))
    {
        cmdSelect.Parameters.Add("@fileBaseName", SqlDbType.VarChar).Value = fbn;

        connection.Open();
        excelContents = (byte[])cmdSelect.ExecuteScalar();
        connection.Close();
    }
    string excelFileName = "C:\\Misc\\TestFile2.xlsx";
    File.WriteAllBytes(excelFileName, excelContents);

    String HtmlToDisplay = GetDownloadSuccessMessage(excelFileName);
    return new HttpResponseMessage()
    {
        Content = new StringContent(
            HtmlToDisplay,
            Encoding.UTF8,
            "text/html"
        )
    };
}

internal static string GetDownloadSuccessMessage(string excelFileName)
{
    return string.Format("<h1>Excel spreadsheed downloaded to {0}</h1>", excelFileName);
}

This works just fine (except that there is no downloading action visible, such as the file's icon dropping to the taskbar, as is normally the case when downloading files from the Internet - the file simply winds up in the location indicated).

My assumption is that this only works because I am running the ASP.NET Web API project locally and so my file system is considered "fair game" for writing.

How can I accomplish the same thing (preferably with the visible downloading heretofore mentioned) on any remote user's machine (obviously, I can't just place the file anywhere, not only for security reasons, but also because I don't know which folders they might have)?

UPDATE

I was going to try this:

HttpResponseMessage httprm = new HttpResponseMessage();
httprm.Buffer = true;
httprm.Charset = "";
httprm.Cache.SetCacheability(HttpCacheability.NoCache);
httprm.ContentType = "application/vnd.ms-excel";
httprm.AddHeader("content-disposition", "attachment;filename=\"Funk49.xlsx\"");
httprm.BinaryWrite(bytes);
httprm.Flush();
httprm.End();

...adapted from here, but none of those properties or methods are part of HttpResponseMessage's milieau. I even tried a raw "Response.Buffer" in place of "httprm.Buffer", hoping the undeclared "Response" object (not declared in the sample code, either) would at least afford me resolvability, but no such serendipity shone on me.

UPDATE 2

I am going to bountify the accepted answer ASAP; it was one of the most helpful ones I've ever gotten. I combined that wisdom with other bits and pieces to compile (no pun intended) a tip that shows how to save Excel data and then read it out again from a Web API app and download it here.

I am trying to write an Web API from .net and trying for my Android Application to query some data from the SQL server database.

I enabled the external service by using this command

netsh http add urlacl url=http://10.71.34.1:63026/ user=everyon

and added the Firewall rule using this command

netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=58938 profile=private remoteip=localsubnet action=allow

The site configuration looks like this

 <site name="YourTimeSite" id="29">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="E:\Downloads\YourTimeSite\YourTimeSite" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation=":63026:" />
                    <binding protocol="http" bindingInformation=":63026:Mujtaba-PC" />
                    <binding protocol="http" bindingInformation=":63026:10.71.34.1" />
                </bindings>
            </site>

When I run the app and go to the url http://10.71.34.1:63026/api/productsI get "HTTP Error 503. The service is unavailable" error.

When I configured it the first time, everything worked fine. I didn't change anything and I'm getting this error. I can access Web api if I replace ip with localhost.

What am I missing here?

How to compare same model value in foreach loop Razor View

@foreach (var item in Model)
{
    <tr id="@(item.ShopListID)">
        <td class="shoptablename">@Html.DisplayFor(modelItem => item.Name)
        </td>
        <td class="shoptableamount">
            @if (item.Amount == item.Amount)
            {
                Html.Display("--");
            }
            else
            {
                String.Format("{0:0.##}", item.Amount);
            }
        </td>
    </tr>

}

I want to check if item.Amount value is equal to item.Amount

I am working in a project and I want to check for user id before let him update or delete. I use Entity Framework and ASP.NET MVC for that.

Table 1 is

public class User {
    public int UserId { get; set; }  

    // more stuff here. 

    public ICollection<UserPost> UserPost{get; set;}
}

Here is my second table

public class Post {
    public int PostId { get; set; } 

    // more stuff 

    public ICollection<UserPost> UserPost{get; set;}
}

This is my last one:

public class UserPost {
    public int userPostId { get; set; }
    public int userId {get; set; }
    public int postId {get; set; }

    public virtual User User { get; set; }
    public virtual User Post{ get; set; }
    // and more 
}

In my view I want to check for user to update or delete his posts like this code but it does not work.

@model List<MyFinalProject.Core.Domain.Post>
// Razor syntax here 
    @if (User.Identity.IsAuthenticated && User.IsInRole("Admin") ||
                            Model[i].UserPost.Where(u => u.UserId == User.Identity.GetUserId<int>()))
                        { // some logic } 

I'm working on a large form that I'm looking to improve the usability of by sectioning it into a jQuery form wizard (jQuery tabbed panels).

I have already implemented both client-side validation and server-side validation. Client side validation is performed on each tabbed panel before moving to the next tabbed panel and server side validation is only performed once the form is posted to the server.

The thing I'm having trouble with is how to best handle server-side validation errors. Currently if the form is posted to the server it returns the form and shows any errors however this doesn't really work to well with jQuery tabbed panels as the tabbed panel resets to its default state once the form is returned.

If the form fails server side validation how do I reload the form and automatically show the tabbed panel in which the inputs that failed server side validation reside. For example, lets say I have three tabbed panels in my form wizard. If an input in the third tabbed panel failed server side validation how do I reload the form with the third tabbed panel shown.

I have tried creating the from wizard server-side where each section has its own view and controller action however however with this approach it much harder to create a navigation bar to move between the form section.

I am creating web application with Identity 3.0 and have problems with SignInManager PasswordSignInAsync() method. I'm using it just like in documentation, but it doesn't return anything ( application code just stop there ) Here`s my controller code:

 public class AppController : Controller
{
    private IAccountService _service;
    private readonly SignInManager<User> _signInManager;
    private UserManager<User> _userManager;

    public AppController(IAccountService service, SignInManager<User> signInManager, UserManager<User> userManager)
    {
        _service = service;
        _signInManager = signInManager;
        _userManager = userManager;
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            var password = await _userManager.CheckPasswordAsync(user, model.Password);

            var result = await _signInManager.PasswordSignInAsync(
                model.Email,
                model.Password,
                model.RememberMe,
                lockoutOnFailure: false);

            if (result.Succeeded)
            {
                return RedirectToAction(nameof(EmployeeController.Contact), "Employee");
            }
            if (result.IsLockedOut)
            {
                return View("Lockout");
            }
            if(result.IsNotAllowed)
            {
                return View("Not Allowed");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }
        return View(model);
    }
}

And configuration in startup.cs file:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddCaching();
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.CookieName = ".MyApplication";
        });

        services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Data:DbContextConnection"]));


        services.AddIdentity<User, UserRole>(config => 
            {
                config.User.RequireUniqueEmail = true;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/App/Login";
                config.SignIn.RequireConfirmedEmail = false;
                config.SignIn.RequireConfirmedPhoneNumber = false;
            })
        .AddEntityFrameworkStores<ApplicationDbContext,string>()
        .AddDefaultTokenProviders();

        services.AddTransient<IAccountService, AccountService>();
    }

public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        app.UseSession();

        app.UseIdentity();
        app.UseMvc(config =>
        {
            config.MapRoute(
                name: "Default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "App", action = "Index" }
                );
        });
    }

Thanks for any help

I have a grid view which contains past, present and future dates. When the page loads, its either sorted ascending, or descending.

How can I set it to show starting from date today then future, but still shows the past dates.

Creating: A handler which checks in database if there's a new messsage.

What I've done so far: Javascript that using AJAX runs a handler every third second.

What I'm unable to do: Returning a result from ASHX handler to AJAX javascript so that I can perform a postback if the result is true.

Here's the Javascript:

    //handle message upload

        window.setInterval(function () {

            $.ajax({
                url: "handlecb.ashx",
                type: "POST",

                success: function (result) {
                    toastr.options = {
                        "closeButton": false,
                        "debug": false,
                        "newestOnTop": true,
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "preventDuplicates": true,
                        "onclick": null,
                        "showDuration": "1300",
                        "hideDuration": "1300",
                        "timeOut": "5300",
                        "extendedTimeOut": "1000",
                        "showEasing": "swing",
                        "hideEasing": "linear",
                        "showMethod": "fadeIn",
                        "hideMethod": "fadeOut"
                    }
                    toastr.info('Online.');

                   if (result < 0) {
                        __doPostBack("<%= senbut.ClientID %>", "");
                        toastr.options = {
                            "closeButton": false,
                            "debug": false,
                            "newestOnTop": true,
                            "progressBar": false,
                            "positionClass": "toast-bottom-left",
                            "preventDuplicates": true,
                            "onclick": null,
                            "showDuration": "1300",
                            "hideDuration": "1300",
                            "timeOut": "5300",
                            "extendedTimeOut": "1000",
                            "showEasing": "swing",
                            "hideEasing": "linear",
                            "showMethod": "fadeIn",
                            "hideMethod": "fadeOut"
                        }
                        toastr.success('New message recieved.');
                    }


                },
                error: function (err) {
                    toastr.options = {
                        "closeButton": false,
                        "debug": false,
                        "newestOnTop": true,
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "preventDuplicates": true,
                        "onclick": null,
                        "showDuration": "1300",
                        "hideDuration": "1300",
                        "timeOut": "5300",
                        "extendedTimeOut": "1000",
                        "showEasing": "swing",
                        "hideEasing": "linear",
                        "showMethod": "fadeIn",
                        "hideMethod": "fadeOut"
                    }
                    toastr.danger('Offline');

                }
            });
        }, 3000);

Here's the Handler:

    <%@ WebHandler Language="VB" Class="handlecb" %>

    Imports System.Data
    Imports System.IO
    Imports System.Data.OleDb
    Imports System.Web.SessionState
    Imports System.Web.Security
    Imports System.Web

        Public Class handlecb
            Implements IHttpHandler, System.Web.Session

State.IRequiresSessionState

    Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ishaan Patel\Desktop\Paperhome\paperhome_data.accdb")


Dim cmd As OleDbCommand
Dim cmd2 As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dr As OleDbDataReader
Dim result As Integer

Public Sub ProcessRequest(ByVal context As HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
    Dim threadid As String
    If Not context.Session("chatsess") Is Nothing Then
        threadid = context.Session("chatsess")
        GoTo b
    Else
        GoTo a
    End If
    b:
    Dim thread As Integer
    thread = Convert.ToInt32(threadid)


    con.Open() 'checklastupdatedon
    cmd = New OleDbCommand("SELECT [last_updated_on] FROM [message_threads] WHERE ([message_threads].[thread_id] = " & thread & ")", con)
    cmd.Connection = con
    dr = cmd.ExecuteReader
    If (dr.Read) Then
        Dim fetched As Date = Convert.ToDateTime(dr("last_updated_on"))
        Dim old As Date = Convert.ToDateTime(context.Session("last_updated_on"))

        result = DateTime.Compare(old, fetched)
        con.Close()

        If result < 0 Then 'old fetched is earlier than timer fetched

            context.Session("last_updated_on") = fetched

        End If

    End If
    a:
End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get




   Return result
    End Get
End Property
 End Class

Any help/suggestion is appreciated. Thank you.

I want to pass an id to QueryString of my webpage, as I don't want visitors to see the number, I encode it using RijndaelManaged algorithm, My issue is, this encryption sometimes add a character for example '+' which causes double escape sequence error. I was wondering if there is way to exclude some characters from encryption output.

My encryption code is as below:

  public static  string Encrypt(string plainText)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

        byte[] cipherTextBytes;

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memoryStream.ToArray();
                cryptoStream.Close();
            }
            memoryStream.Close();
        }
        return Convert.ToBase64String(cipherTextBytes);
    }

i have a ActionResult to edit a Group, all groups have a id, to know which information to display to each group my ActionResult takes a int id to referer to the correct group. And on the view that display the group information i have a textbox in which im using the jquery autocomplete to search for users, and here is the problem the jquery autocomplete isn't working, but in other view with diferente actionResult but the exact same code is working. So i when i was trying to do debugging i realize that the jquery autocomplete doesnt find the correct path if the action result takes some parameter.

Can someone help me to resolve this problem ? thanks :)

Here is my code:

View:

       <head>
        <link rel="stylesheet" href="~/Content/jquery-ui.css">
        <script src="~/scripts/jquery-2.2.2.js"></script>
        <script src="~/scripts/jquery-ui-1.11.4.js"></script>

        <script>
      $(function() {
        function split( val ) {
          return val.split( /,\s*/ );
        }
        function extractLast( term ) {
          return split( term ).pop();
        }

        $( "#Search" )
          .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
          })
          .autocomplete({
            source: function( request, response ) {
                $.getJSON("AutoCompleteUsers", {
                term: extractLast( request.term )
              }, response );
            },
            search: function() {
              var term = extractLast( this.value );
              if ( term.length < 2 ) {
                return false;
              }
            },
            focus: function() {
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              terms.pop();
              terms.push(ui.item.value);
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
          });
      });
        </script>
    </head>
    <body>

     <div class="input-group">
     <input id="Search" type="text" class="form-control">
  </div>
   </body>

And this is my controller:

 public ActionResult EditGroup(int id)
        {
.....
}
public JsonResult AutoCompleteUsers(string term)
        {

            var result = (from r in db.Utilizadors
                          where r.Nome.ToLower().Contains(term.ToLower())
                          select new {  value = r.Nome, userId = r.id_utilizador, image = r.imagem }).Distinct();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

Screenshots from firefox debugging:

ActionResult without parameters working ActionResult without parameters

ActionResult with parameters(int id) not working ActionResult with parameters(int id)

Currently I can properly send an HTML email with ASP.net. I noticed that using a spam tester such https://www.mail-tester.com/ would give a better score if you supplied both a plain text view as well as the HTML view. So i decided to try to add the alternate views. My issues is that if I try and add a plain text view it seems to override the HTML View. Here is the code that works perfectly fine for setting up my HTML only view:

    message.IsBodyHtml = true;
    message.BodyEncoding = Encoding.UTF8;
    message.BodyTransferEncoding = TransferEncoding.Base64;
    message.Body = "<html lang=\"en\"><head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head><body>" + message.Body + "</body></html>";

Now if I try to add the plain view Gmail seems to only want to display the plain text view and not the HTML view. Is there anyway to set which view is default? Here is my plain text view code:

    message.IsBodyHtml = true;
    message.BodyEncoding = Encoding.UTF8;
    message.BodyTransferEncoding = TransferEncoding.Base64;
    message.Body = "<html lang=\"en\"><head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head><body>" + message.Body + "</body></html>";

    //first we create the Plain Text part
    var plainView = AlternateView.CreateAlternateViewFromString(HtmlToPlainText(message.Body), Encoding.UTF8, MediaTypeNames.Text.Plain);
    ////then we create the Html part
    var htmlView = AlternateView.CreateAlternateViewFromString(message.Body, Encoding.UTF8, MediaTypeNames.Text.Html);
    message.AlternateViews.Add(htmlView);
    message.AlternateViews.Add(plainView);

I have tried removing first displayed code for the body and setting the body to empty string so that it only adds both of the alternate views and that did not work. I believe I covered all permutations of the code and still nothing. Like I said it works perfectly for HTML only and it works with html alternate view but not when adding the plain text view.

I got an assignment to compare the MVC, web form and razor (web pages) in terms of syntax rule.

Any help?

I'm currently implementing a Family Tree system in my ASP.NET MVC project. In order to set the relationship between family members, I need to display two ComboBox/DropDownList per row to define relationships from one member to the other.

First I will share my codes and then I will explain what ways I've tried so far and what was the result at the end.

ViewModel

public class FamilyTreeRelationshipViewModel
{

    [ScaffoldColumn(false)]
    public string FromMemberId { get; set; }

    [ScaffoldColumn(false)]
    public string ToMemberId { get; set; }


    public Member FromMember { get; set; }
    public IEnumerable<Member> ToMembers { get; set; }


    [UIHint("FTComboBox")]
    [AdditionalMetadata("BindTo", "relationships")]
    [Required]
    [Display(Name = "From Relationship")]
    public string FromRelationship { get; set; }


    [UIHint("FTComboBox")]
    [AdditionalMetadata("BindTo", "relationships")]
    [Required]
    [Display(Name = "To Relationship")]
    public string ToRelationship { get; set; }
}

Controller

public class FamilyTreeController : Controller
{
    private AppMVC db = new AppMVC();


    public ActionResult Index(Guid? cid, Guid? mid)
    {

        if (cid == null && mid == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }


        var frommember = db.Member.FirstOrDefault(x => x.MemberId == mid && x.CaseId == cid && x.Deleted == false);
        var tomembers = db.Member.Where(x => x.CaseId == cid && x.MemberId != mid.Value && x.Deleted == false).ToList();


        ViewBag.cid = cid;
        ViewBag.mid = mid;

        PopulateRelationship();


        var familyTreeRelationshipViewModel = new FamilyTreeRelationshipViewModel
        {
            FromMember = frommember,
            ToMembers = tomembers,
        };

        return View(familyTreeRelationshipViewModel);
    }



    public void PopulateRelationship()
    {
        var relationship = db.RelationshipDD
        .Where(c => c.Deleted == false && c.Code != "PA")
        .OrderBy(c => c.OrderIndex)
        .Select(c => new RelationshipDDViewModel
        {
            Code = c.Code,
            Definition = c.Definition
        })
        .ToList();

        ViewData["relationships"] = relationship;

    }

}

Editor Template for ComboBox

@model object

@{
    var bindto = ViewData.ModelMetadata.AdditionalValues["BindTo"].ToString();
    var fieldname = ViewData.ModelMetadata.PropertyName;
    var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;

}

@(Html.Kendo().ComboBoxFor(m => m)
          .Filter("contains")
          .Placeholder(ViewData.ModelMetadata.DisplayName)
          .DataTextField("Definition")
          .DataValueField("Code")
          .HtmlAttributes(new { style = "width: 100%", Id = prefix})
          .BindTo((System.Collections.IEnumerable)ViewData[bindto])

          )

@Html.ValidationMessageFor(m => m, "", new { @class = "mdc-text-red-400" })

In order to show each row a new result, I used foreach in View:

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        foreach (var othermembers in Model.ToMembers.OrderBy(x => x.MemberNumberSuffix))
        {
            @Html.EditorFor(m => m.ToRelationship)
            @Html.EditorFor(m => m.FromRelationship)
        }
    }
}

As you see below in the screenshot, only ComboBoxes in the first row were rendered. I assume it's because of the same control Id for each ComboBox. I checked the browser developer tools (F12), all of them had the same Id. ForEach

Later I thought I should use For instead of Foreach and see what happens:

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        for (var i = 0; i < Model.ToMembers.Count(); i++)
        {
            var othermembers = Model.ToMembers.ToList()[i];

            @Html.EditorFor(m => m.ToRelationship[i])
            @Html.EditorFor(m => m.FromRelationship[i])
        }
    }
}

As you see below in the screenshot, all of the ComboBoxes are gone and everything has been rendered as Char. The only difference here is that each control/input has it's own Id and that's good but not good as I was expecting. For

After all, I decided to use the Built-in DropDownList (MVC) for this purpose and it was the same result. Because I thought something is wrong with Telerik controls.

I even tried to use the ComboBox directly inside the View instead of EditorFor, the result was different. Each row was rendered separately and successfully but it was again Char type and even the error message says that. Normally it should say, "From relationship field is required".

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        for (var i = 0; i < Model.ToMembers.Count(); i++)
        {

            @(Html.Kendo().ComboBoxFor(m => m.ToRelationship[i])
            .Filter("contains")
            .Placeholder(ViewData.ModelMetadata.DisplayName)
            .DataTextField("Definition")
            .DataValueField("Code")
            .HtmlAttributes(new { style = "width: 100%" })
            .BindTo((System.Collections.IEnumerable)ViewData["relationships"])
            )

            @(Html.Kendo().ComboBoxFor(m => m.FromRelationship[i])
            .Filter("contains")
            .Placeholder(ViewData.ModelMetadata.DisplayName)
            .DataTextField("Definition")
            .DataValueField("Code")
            .HtmlAttributes(new { style = "width: 100%" })
            .BindTo((System.Collections.IEnumerable)ViewData["relationships"])
            )
        }
    }
}

Screenshot: For Direct


Questions

  1. Why can't I use EditorFor for this purpose?
  2. Why the type has changed to Char and how can I fix this?
  3. Any alternative way to achieve this?

Thanks in advance for your help!

when I trying to create two ad rotator in the same project I do not no how! because Xml file take the only name (Advertisements.XML) and also has one root element(Advertisements) that take in one Ad Rotator so How can I create another one

When the user signs up to my website using Facebook I want to store their Facebook ID as a claim in my database.

Startup.auth:

 var fbOptions = new FacebookAuthenticationOptions()
        {
            AppId = GlobalConstants.APP_ID,
            AppSecret = GlobalConstants.APP_SECRET,
            Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new Claim(CustomClaims.FacebookId, context.Id));
                    return Task.FromResult(0);
                }
            },
        };
        app.UseFacebookAuthentication(fbOptions);

I have debugged this, and I see that I am correctly retrieving the Facebook ID.

Then the user is presented with the ExternalLoginCallback (which simply asks them to input an email to finish the registration) (default Asp.NET code)

Then, the ExternalLoginConfirmation method is called, which creates the user. Just before I call StoreAndUpdateCustomClaims:

await StoreAndUpdateCustomClaims(user);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

StoreAndUpdateCustomClaims:

 private async Task StoreAndUpdateCustomClaims(ApplicationUser user)
    {
        // Get the claims identity
        ClaimsIdentity claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
        if (claimsIdentity != null)
        {
            // Retrieve the existing claims
            var currentClaims = await UserManager.GetClaimsAsync(user.Id);

            foreach(var claim in claimsIdentity.Claims)
            {
                if(claim.Type == CustomClaims.FacebookId)
                {
                    if(!currentClaims.Contains(claim))
                    {
                        await UserManager.AddClaimAsync(user.Id, claim);
                    }
                }
            }
        }
    }

As you see, I check to see if there's a Facebook ID claim (which I added in OnAuthenticated in Startup.Auth). However, the Facebook ID claim is non existent!

What am I doing wrong?

Sorry excuse my knowledge, but what does creating a standalone ASP.NET Static or Dynamic DropDownList (or other server controls) that could be inserted / shared between user many controls where I can modify, or "Data Bind" it from one single code file called? Is it custom DropDonList control?

I need to have DropDownLists (to dynamically bind its items sometimes and with static items some times) that can be inserted in my project user controls then modify it from one place.

Any examples? from where I start with my starter knowledge?

Example

Need to call this in my forms with AutoPostBack = true and its SelectedIndexChanged event code will be in my user control code behind.

    <asp:DropDownList id="ddlLang" runat="server" AutoPostBack="True" CssClass="select-normal">
        <asp:ListItem Value="1" Text="<%$ Resources:cmsLocale, English %>"></asp:ListItem>
        <asp:ListItem Value="3" Text="<%$ Resources:cmsLocale, French %>"></asp:ListItem>
        <asp:ListItem Value="4" Text="<%$ Resources:cmsLocale, German %>"></asp:ListItem>
    </asp:DropDownList>

Uisng regex in c# i want to extract page value from last anchor tag? This is the code:

<nav class="pagination shop">
            <ul><div id="results_bottom"><li style="display: inline-block;"><a class="btn current"  href="?swift=&country=india&bank=&page=1">1</a> <a class="btn"  href="?swift=&country=india&bank=&page=2">2</a> <a class="btn"  href="?swift=&country=india&bank=&page=3">3</a> <a class="btn"  href="?swift=&country=india&bank=&page=4">4</a> <a class="btn"  href="?swift=&country=india&bank=&page=5">5</a> <a class="btn"  href="?swift=&country=india&bank=&page=6">6</a> <a class="btn"  href="?swift=&country=india&bank=&page=7">7</a> <a class="btn"  href="?swift=&country=india&bank=&page=8">8</a> <a class="btn"  href="?swift=&country=india&bank=&page=9">9</a> <a href="?swift=&country=india&bank=&page=2">Next &rarr;</a><a href="?swift=&country=india&bank=&page=193">Last &raquo;</a></li></div></ul></nav>

"What I need is "193" from

<a href="?swift=&country=india&bank=&page=193">Last &raquo;</a>

Thanks in adavnce

I'm using Windows 2012 server and my app asp.net framework 4.0 use SQL sever session mode. If 1 user login everything is OK, but if user 2 login in same time the user(1) found session information of user (2)!

The session save information about last login only!

How to Crete special session for every user?

I'm currently implementing a Family Tree system in my ASP.NET MVC project. In order to set the relationship between family members, I need to display two ComboBox/DropDownList per row to define relationships from one member to the other.

First I will share my codes and then I will explain what ways I've tried so far and what was the result at the end.

ViewModel

public class FamilyTreeRelationshipViewModel
{

    [ScaffoldColumn(false)]
    public string FromMemberId { get; set; }

    [ScaffoldColumn(false)]
    public string ToMemberId { get; set; }


    public Member FromMember { get; set; }
    public IEnumerable<Member> ToMembers { get; set; }


    [UIHint("FTComboBox")]
    [AdditionalMetadata("BindTo", "relationships")]
    [Required]
    [Display(Name = "From Relationship")]
    public string FromRelationship { get; set; }


    [UIHint("FTComboBox")]
    [AdditionalMetadata("BindTo", "relationships")]
    [Required]
    [Display(Name = "To Relationship")]
    public string ToRelationship { get; set; }
}

Controller

public class FamilyTreeController : Controller
{
    private AppMVC db = new AppMVC();


    public ActionResult Index(Guid? cid, Guid? mid)
    {

        if (cid == null && mid == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }


        var frommember = db.Member.FirstOrDefault(x => x.MemberId == mid && x.CaseId == cid && x.Deleted == false);
        var tomembers = db.Member.Where(x => x.CaseId == cid && x.MemberId != mid.Value && x.Deleted == false).ToList();


        ViewBag.cid = cid;
        ViewBag.mid = mid;

        PopulateRelationship();


        var familyTreeRelationshipViewModel = new FamilyTreeRelationshipViewModel
        {
            FromMember = frommember,
            ToMembers = tomembers,
        };

        return View(familyTreeRelationshipViewModel);
    }



    public void PopulateRelationship()
    {
        var relationship = db.RelationshipDD
        .Where(c => c.Deleted == false && c.Code != "PA")
        .OrderBy(c => c.OrderIndex)
        .Select(c => new RelationshipDDViewModel
        {
            Code = c.Code,
            Definition = c.Definition
        })
        .ToList();

        ViewData["relationships"] = relationship;

    }

}

Editor Template for ComboBox

@model object

@{
    var bindto = ViewData.ModelMetadata.AdditionalValues["BindTo"].ToString();
    var fieldname = ViewData.ModelMetadata.PropertyName;
    var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;

}

@(Html.Kendo().ComboBoxFor(m => m)
          .Filter("contains")
          .Placeholder(ViewData.ModelMetadata.DisplayName)
          .DataTextField("Definition")
          .DataValueField("Code")
          .HtmlAttributes(new { style = "width: 100%", Id = prefix})
          .BindTo((System.Collections.IEnumerable)ViewData[bindto])

          )

@Html.ValidationMessageFor(m => m, "", new { @class = "mdc-text-red-400" })

In order to show each row a new result, I used foreach in View:

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        foreach (var othermembers in Model.ToMembers.OrderBy(x => x.MemberNumberSuffix))
        {
            @Html.EditorFor(m => m.ToRelationship)
            @Html.EditorFor(m => m.FromRelationship)
        }
    }
}

As you see below in the screenshot, only ComboBoxes in the first row were rendered. I assume it's because of the same control Id for each ComboBox. I checked the browser developer tools (F12), all of them had the same Id. ForEach

Later I thought I should use For instead of Foreach and see what happens:

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        for (var i = 0; i < Model.ToMembers.Count(); i++)
        {
            var othermembers = Model.ToMembers.ToList()[i];

            @Html.EditorFor(m => m.ToRelationship[i])
            @Html.EditorFor(m => m.FromRelationship[i])
        }
    }
}

As you see below in the screenshot, all of the ComboBoxes are gone and everything has been rendered as Char. The only difference here is that each control/input has it's own Id and that's good but not good as I was expecting. For

After all, I decided to use the Built-in DropDownList (MVC) for this purpose and it was the same result. Because I thought something is wrong with Telerik controls.

I even tried to use the ComboBox directly inside the View instead of EditorFor, the result was different. Each row was rendered separately and successfully but it was again Char type and even the error message says that. Normally it should say, "From relationship field is required".

@if (Model.ToMembers != null)
{
    if (Model.ToMembers.Any())
    {
        for (var i = 0; i < Model.ToMembers.Count(); i++)
        {

            @(Html.Kendo().ComboBoxFor(m => m.ToRelationship[i])
            .Filter("contains")
            .Placeholder(ViewData.ModelMetadata.DisplayName)
            .DataTextField("Definition")
            .DataValueField("Code")
            .HtmlAttributes(new { style = "width: 100%" })
            .BindTo((System.Collections.IEnumerable)ViewData["relationships"])
            )

            @(Html.Kendo().ComboBoxFor(m => m.FromRelationship[i])
            .Filter("contains")
            .Placeholder(ViewData.ModelMetadata.DisplayName)
            .DataTextField("Definition")
            .DataValueField("Code")
            .HtmlAttributes(new { style = "width: 100%" })
            .BindTo((System.Collections.IEnumerable)ViewData["relationships"])
            )
        }
    }
}

Screenshot: For Direct


Questions

  1. Why can't I use EditorFor for this purpose?
  2. Why the type has changed to Char and how can I fix this?
  3. Any alternative way to achieve this?

Thanks in advance for your help!