vendredi 30 septembre 2016

Why is my MultiSelectList not returning data to model?

I have the following View Model:

public class SendGroupEmailViewModel
{
    public int EmailID { get; set; }
    public IEnumerable<SelectListItem> Roles { get; set; }
    public int[] SelectedRoles { get; set; }

}

The controller action that sends the appropriate information to the view:

var viewModel = new SendGroupEmailViewModel
        {
            Roles = db.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),

        };

Then in my view:

@Html.ListBoxFor(model => model.SelectedRoles, new MultiSelectList(Model.Roles, "Value", "Text"), new { @class = "" })

The list appears correctly within the view but when the form with the above ListBoxFor in is posted SelectedRoles returns as null.

Can anyone tell me why this is and how I can remedy it?

What is the correct way to use Linq to reference the table you instantiate with your ViewModel as a list to generate a list of 'SelectListItems'?

I want to generate a strongly typed list of Roles in my controller along with two other lists which will be used in my view as various filters for sending an email. I'm aware I can generate the Roles list using the following:

var viewModel = new ListViewModel
        {
            Roles = db.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),
        };

However as I am also wanting to pass two other lists to my controller I would prefer to attain the list of roles by writing the query in the following way:

var viewModel = db.Roles

           .Select(x => new SendGroupEmailViewModel
           {
               Roles = x.Roles.Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),

           };

That way I can then attain my other two lists as part of the same query, as opposed to the previous method where they would have to be effectively separate queries to the db. Obviously what is above doesn't work, I am unable .Select on the role table by writing Roles = x.Select.

My question is, why am I unable to do this and what is the correct way to query the Roles table when writing it in a similar way to the above?

Just to be clear, the reason it has to be var viewModel = db.Roles is because for whatever reason I can't access the ID/Name Roles list otherwise due to how Identity is setup in MVC. I know there are other ways of attaining the list, I would just like to know how it can be done this specific way?

jeudi 29 septembre 2016

what are the things to take care of when migrating from asp.net 3.5.2 to asp.net 4.5.2?

what are the changes required in web.config? and other things to take care of when migrating from asp.net 3.5.2 to asp.net 4.5.2?

I directly did that and it giving errors.

mercredi 28 septembre 2016

Access Sharepoint Docuemnts of logged-in user

I have a MVC application where a list of users can upload files to GoogleDrive/DropBox and for this they just need to authenticate themselves and the corresponding api provides an 'AccessToken' or something which is further used to upload files to user account from my web application.

Now I need to do same thing with Microsoft Sharepoint. For testing I created an account there and can get the ClientContext like this

public void GetSharePointContext()
    {
        using (ClientContext context = new ClientContext("http://ift.tt/1nx25wI"))
        {
            context.Credentials = new NetworkCredential("anil.dutt@test.onmicrosoft.com", "somepassword", "https://test.dev.com/");
            List list = context.Web.Lists.GetByTitle("Some List");
            context.ExecuteQuery();

            // Now update the list.
        }
    }

Now I want to make user who logged into my app, can do same.

So in case of Microsoft Sharepoint what can I do to authenticate the logged in user on Sharepoint account and get his/her site url to get documents and perform upload/download etc.

For this i will open a sharepoint window where user will login but how to get Site URL like 'http://ift.tt/1nx25wI'.

Please advice

mardi 27 septembre 2016

Can QR Code Reader in mobile phone function like a Barcode Reader?

I try before to use a barcode reader to read a barcodes and it is working fine. I am thinking that how can I use QR Code Reader from my mobile phone to scan the qr code image and the scan image(data) will search in my project. In Barcode Reader I try it before but in windows and barcode reader is connecting to my pc or laptop how about my mobile phone how do I set it?.

BTW I am developing a asp.net mvc3 project.

lundi 26 septembre 2016

The specified message does not exist. ErrorCode:MessageNotFound Prod-WorkerError Context

I have a worker role which consumes messages from an Azure Queue does some processing in the background. When I check my log there appears to be no exception logged while processing the message but still in my logs I get the following Exception(pasting some of the relevant texts from the long error log only):

System.Net.WebException Microsoft.WindowsAzure.Storage.StorageException Exception messages: The remote server returned an error: (404) Not Found. The remote server returned an error: (404) Not Found. Stack Traces: at System.Net.HttpWebRequest.GetResponse() at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) --- Next Call Stack: at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) at Microsoft.WindowsAzure.Storage.Queue.CloudQueue.DeleteMessage(String messageId, String popReceipt, QueueRequestOptions options, OperationContext operationContext) at InnovativeExams.Azure.CloudStorage.AzureQueue`1.DeleteMessage(T message) The specified message does not exist. ErrorCode:MessageNotFound Prod-WorkerError Context

Here is the code I have in the worker role:

private void ProcessQueueMessage(object queueMessageToProcess)
        {
            var queueMessage = queueMessageToProcess as EventCompletedQueueMessage;

            try
            {
                if (_eventCompletedProcessor.Process(queueMessage))
                    _azureQueue.DeleteMessage(queueMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(string.Format("Event Completed message <{0}> was not processed due to an exception", queueMessage.Id), ex, LogSources.WorkerRole_EventCompletedDispatcher);
            }
        }

The above exception is caught in the above catch block and logged.

I think there is some problem when the worker role tries to Delete the message in the Queue and the message is not found.

Need help from someone to help me resolve this error and to know the background what's going wrong here.

dimanche 25 septembre 2016

How do I pass checked checkbox to the controller when dealing with a list?

I am trying to created check boxes for items in my list. Basically when a user is creating a task he will have a list of contacts(existing users he added) with check boxes. He will then check which users he wants to share the task with.

Model:

 public class UserTask
{
    [Key]
    public int UserTaskID { get; set; }

    [Required]
    public string ApplicationUserID { get; set; }

    [Required]
    [StringLength(20, ErrorMessage ="Can't exceed 20 characters")]
    [Display(Name = "Task Name")]
    public string Title { get; set; }

    [Column(TypeName = "date")]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    [Display(Name = "Done")]
    public bool Status { get; set; }

public virtual ICollection<TaskInvitee> TaskInvitees { get; set; } //Ignore 
}

ViewModel:

public class TaskViewModel
{
   public int UserTaskID { get; set; }

   public string ApplicationUserID { get; set; }

   public string Title { get; set; }

   public DateTime Date { get; set; }

   public bool Status { get; set; }

    public bool Selected { get; set; }
    public List<ApplicationUser> users { get; set; }
}

Controller Create: Long story short this code gets only the contacts that belong to the current users and matches them with all existing users so that I can extract their first name, last name and email details then I pass it to the ViewModel.

 public ActionResult Create()
    {
        IEnumerable<ApplicationUser> users = db.Users.ToList();

        IEnumerable<Contact> contacts = db.Contacts.ToList().Where(c => c.ApplicationUserID.Equals(User.Identity.Name));

        List<ApplicationUser> curUsers = new List<ApplicationUser>();

        foreach (var contact in contacts)
        {
            foreach (var user in users)
            {
                if (contact.ContactUserID.Equals(user.UserName))
                {
                    curUsers.Add(user);
                }
            }
        }

        TaskViewModel tvm = new TaskViewModel();
        tvm.users = curUsers;

        return View(tvm);
    }

Controller Create Post: Now assuming what I did in my create view is correct how do I pass to this controller and check which contacts have been checked?

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "UserTaskID,ApplicationUserID,Title,Date,Status")] UserTask userTask)
    {
        if (!String.IsNullOrWhiteSpace(userTask.Title))
        {
            userTask.ApplicationUserID = User.Identity.Name;
            userTask.Date = DateTime.Today;
            userTask.Status = false;
            db.UserTasks.Add(userTask);
            db.SaveChanges();

          //foreach(var item in list)
          //  {
          //      if(item.Selected)
          //      {
           //       pass to share action
          //      }
          //  }
            return RedirectToAction("Index");
        }

        return View(userTask);
    }

Create view: If what I did here at the "Invited contacts" heading is not correct then how to I go about adding check boxes to each contact when dealing with a list?

 @model MySchedule.ViewModels.TaskViewModel

  @using (Html.BeginForm())
  {
  var users = Model.users;
  @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Add Task</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model=> model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

 <div class="form-group">
            <h2>Invited Contacts</h2>
        <table class="table">

            @foreach (var item in users)
            {
                <tr>
                    <td>@Html.EditorFor(model => model.Selected)</td>
                    <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                    <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                    <td>@Html.DisplayFor(modelItem => item.Email)</td>
               </tr>
           }
        </table>
</div>
    </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add" class="btn btn-default" />
            </div>
        </div>
      }
   <div>
     @Html.ActionLink("Cancel", "Index")
      </div>

Any help is greatly appreciated

How to adjust only Image icon in Navigation menu?

I created Navigation menu. In my navigation menu and I want to move only image icon. I tried but it is not moving exactly and whole division is moving. I need to move only image icon from top to bottom.

This is menu

Thank you ...

samedi 24 septembre 2016

This field name is not known- Crystal Report

i'm using VS2013 - CR12

i make 2 total summery fields in my Crystal and working well Preview And Publish

when i Make formula to give me subtracting between this summery

fields in preview Working well

in publish give me this error

This field name is not known. Details: errorKind Error in File temp_e612bcb8-bec6-4cb3-8578-3ccbb283dddc 2260_8300_{1DA56A4D-D201-4574-89F9-B39CAACCF547}.rpt: Error in formula Dif: ' ' This field name is not known. Details: errorKind

plz some one healp me

vendredi 23 septembre 2016

Add default route in IIS

When I deploy my MVC3 web site on IIS 7.5 and click on browse (on port 80), my browser display the web site with localhost url (or serverName url) but my default route is like that :

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
        "Default",
        "{lang}/{controller}/{action}",
        new { controller = "Home", action = "Index", lang = Thread.CurrentThread.CurrentUICulture.ToString().Substring(0,2)}
        );

    }

Is there an mean in IIS to have full url when I click on browse, i would like to automatically add /fr/Home/Index.

Thanks

jeudi 22 septembre 2016

How to save special characters in c# asp.net

I have this JS code below to save the data input by a user. All data is seen in var JsonData = JSON.stringify(data);. I input a special character in Task (& sign) [Task Value is (A & B)]. But in my controller It cut the data before the & sign.

$('#btn_SubmitOT').live('click', function () {
    if (lastSel != -1) {
        $('#' + lastSel + '_isValidated').val(true);
        //            $('#' + lastSel + '_RequestedBy').val();
        var datefiled = $('#ot_dateFiled').val().
        $('#' + lastSel + '_OTDateApplied').val(datefiled);
        jQuery('#grdOTApplication').saveRow(lastSel, false, 'clientArray');
    }
    var task = $("#task_ot").val();
    //var data = $("#grdOTApplication").jqGrid('getRowData');
    var data = {
        DateFiled: $("#ot_dateFiled").val(),
        DateofOvertime: $("#ot_dateOfOT").val(),
        EmployeeId: $("#empApplicants").val(),
        In1: $("#from_sup").val() + $("#from_AM_PM").val(),
        Out1: $("#to_sup").val() + $("#to_AM_PM").val(),
        EstimatedHours: $("#estimateHrsWrk_ot").val(),
        SpecificTask: task,
        ApprovedBy: $("#approveofficial").val() != null ? $("#approveofficial").val() : 0,
        RecommendedBy: $("#recommenders").val() != null ? $("#recommenders").val() : 0,
        SupervisedBy: $("#immediatesupervisor").val() != null ? $("#immediatesupervisor").val() : 0,
        IsCOC: $('#cmbCO').val() == 1 ? true : false
    }


    var JsonData = JSON.stringify(data);

    var urlPA = '../Request/saveOvertimeRequest?overtimeRequest=' + JsonData + '&_role = 3;

    $.ajax({
        type: "GET",
        url: urlPA,
        success: function (response) {
            alert(response);
            $("#grdOTApplication").trigger("reloadGrid", [{
                current: true
            }]);
            $("#grdOTHistory").trigger("reloadGrid", [{
                current: true
            }]);
            $("#ot_dateOfOT").val("");
            $("#from_sup").val("__:__");
            $("#to_sup").val("__:__");
            $("#estimateHrsWrk_ot").val("");
            $("#task_ot").val("");
        },
        error: function (response) {
            alert("Error");
        },
        datatype: "text"
    });
});

Here is my Controller code I put a breakpoint and debug it why after the it reach in this code ovt = jss.Deserialize<OvertimeRequest>((string)overtimeRequest); it direct to the catch. And as I mention above it it cuts the data before the the & sign.

public String saveOvertimeRequest(String overtimeRequest, int _role)
    {
        Nullable<DateTime> MyNullableDate = null;
        try
        {
            Int32 requestedBy = Convert.ToInt32(HttpContext.Current.Session["PersonId"]);
            Int32 empId = Convert.ToInt32(HttpContext.Current.Session["EmpId"]);

            OvertimeRequest ovt = new OvertimeRequest();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ovt = jss.Deserialize<OvertimeRequest>((string)overtimeRequest);
            ovt.IsFromESS = true;
            ovt.RequestedBy = requestedBy;
            if (_role == 3 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && ovt.RecommendedBy > 0 && ovt.ApprovedBy > 0))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;

            }
            if (_role == 4 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && (ovt.RecommendedBy == 0 || ovt.RecommendedBy == null) && ovt.ApprovedBy > 0))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;
                ovt.RecommendedBy = null;
                ovt.DateRecommend = DateTime.Now;

            }
            if (_role == 5 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && (ovt.RecommendedBy == 0 || ovt.RecommendedBy == null) && (ovt.ApprovedBy == 0 || ovt.ApprovedBy == null)))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;
                ovt.RecommendedBy = null;
                ovt.DateRecommend = DateTime.Now;
                ovt.ApprovedBy = null;
                ovt.DateApproved = DateTime.Now;
                ovt.IsPosted = true;
                ovt.DatePosted = DateTime.Now;
            }
            try
            {
                db.AddToOvertimeRequests(ovt);
                db.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
          }
        catch (Exception e)
        {
            return "An error has occured while sending your request.";
        }
    }

JS

Control

How to implement user logout automatically and redirect to login page on inactivity using global.ascx and web.config in mvc?

I need to logged out the user after the inactivity of 5 minutes. I tried using

and PageBase class like in this link http://ift.tt/1Dp6UDZ

But inheriting this PageBase class in every page is not possible in my big project. Is there any other method to do the logout after few minutes of inactivity? It should be applicable to whole big project other than writing the code inside each page or inheriting everypage from some base class?

ASP.NET MVC3 Forms Authentication Expiring Prematurely

We have an online assessment platform built with MVC3. It runs in IIS on a single dedicated server running Windows Server 2012 R2 over which we have full control. Recently users have been reporting that they are "getting logged out" during assessments.This is a problem as many of our assessments have time constraints and logging back in costs users valuable seconds.

I have been unable to replicate the issue during testing, but have confirmed by consulting our logs that for the last 2 months ~15-20% of users have to log back in at some point during their assessment. For the 10 months prior to that only <2% had to log back in.

I have compared our current code base to how it was 3 months ago, and nothing that is even remotely related to logging in and authentication has been changed. To my knowledge no settings on the server have been changed.

There are many hundreds of files, and thousands of lines of code in this application, but I will try and share the relevant bits in the hope that someone can help me resolve this. If there is any information that I have missed, leave a comment and I will add it as soon as possible.

From Web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Login/" timeout="300" slidingExpiration="true" />
</authentication>

This is how we create the auth cookie:

Guid User_Id = /* lookup id with username after verification */
string User_Role = /* CSV specifying the roles the user has */
DateTime Expiry = DateTime.Now.AddHours(5);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, User_Id.ToString(), DateTime.Now, Expiry, false, User_Role, "/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
cookie.Expires = Expiry; 
HttpContext.Current.Response.Cookies.Add(cookie);

We user a custom implementation of the AuthorizeAttribute to restrict access to most actions like this:

public class MyController : Controller
{
    [CustomAuthorize(Roles = "MyRole")]
    public ActionResult MyAction()
    {
        // do some stuff
        return View();
    }
}

Which defined as follows:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        string cookieName = FormsAuthentication.FormsCookieName;

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
            filterContext.HttpContext.Request.Cookies == null ||
            filterContext.HttpContext.Request.Cookies[cookieName] == null
        )
        {
            HandleUnauthorizedRequest(filterContext);
            return;
        }

        var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string[] roles = authTicket.UserData.Split(',');

        var userIdentity = new GenericIdentity(authTicket.Name);
        var userPrincipal = new GenericPrincipal(userIdentity, roles);

        filterContext.HttpContext.User = userPrincipal;
        base.OnAuthorization(filterContext);
    }
}

This has been the setup for the last 3 years, and it has only been the last 2 months that have been problematic. As you can see the cookie is set to expire 5 hours after its creation. Users have been typically pretty vague with their reports, and looking at our logs the amount of time between initial login and having to login again ranges from anywhere between a few minutes and a couple of hours. Even so I have had a look on the server at what I think are the relevant settings and can't see any thing that may cause a problem:

IIS Settings

If any one has any ideas at all I would love to hear them.

given value of type String from the data source cannot be converted to type datetime of the specified target column

Please need your help in urgent.

facing the issue 'The given value of type String from the data source cannot be converted to type datetime of the specified target column while inserting data into database using sqlbulkcopy.' only in one server, for other server and also in my dev environment everything working fine.

   using (SqlBulkCopy sbc = new SqlBulkCopy(DbSqlConn))
                       {
                           DbSqlConn.Open();

                           // inserting data into table IT000
                           sbc.DestinationTableName = strschema + StoredProcedureNames.UPLOADTABLEGENERICHRIT000;

                           // Number of records to be processed in one go
                           sbc.BatchSize = tblUploadData.Rows.Count;


                           sbc.ColumnMappings.Add("txtEmployeeNo", "txtEmployeeNo");
                           sbc.ColumnMappings.Add("txtCompany", "txtCompany");
                           sbc.ColumnMappings.Add("txtEmpTypeCode", "txtEmpTypeCode");
                           sbc.ColumnMappings.Add("intProcessId", "intProcessId");
                           sbc.ColumnMappings.Add("txtBatchID", "txtBatchID");
                           sbc.ColumnMappings.Add("intUploadType", "intUploadType");

                           sbc.ColumnMappings.Add("intSubTypeSAP", "intSubTypeSAP");
                           sbc.ColumnMappings.Add("txtReasonSAPCode", "txtReasonCode");
                           sbc.ColumnMappings.Add("txtReasonSAPCode", "txtReasonSAPCode");

                          // sbc.ColumnMappings.Add("txtEmployeeSubGroup", "txtEmployeeSubGroup");

                           sbc.ColumnMappings.Add("dtStartDate", "dtStartDate");
                           sbc.ColumnMappings.Add("txtCreatedBy", "txtCreatedBy");
                           sbc.ColumnMappings.Add("dtCreatedDate", "dtCreatedDate");
                           sbc.ColumnMappings.Add("dtLastModifiedDate", "dtLastModifiedDate");
                           sbc.ColumnMappings.Add("txtLastModifiedBy", "txtLastModifiedBy");

                           sbc.ColumnMappings.Add("flgInfoTypeEvent", "flgInfoTypeEvent");
                           sbc.ColumnMappings.Add("txtReferenceKey", "txtReferenceKey");
                           sbc.ColumnMappings.Add("flgstatus", "flgstatus");
                           sbc.ColumnMappings.Add("txtRemarks", "txtRemarks");
                           sbc.ColumnMappings.Add("flgModified", "flgModified");
                           sbc.WriteToServer(tblUploadData);
                           intRes = 1;
                           sbc.Close();
                           DbSqlConn.Close();

                       }

Thanks in advance.

Validation based on dropdown value selected in javascript

i have following values in my dropdown : AX, CA, DC, TS, TP, VI

there is one textbox. based on dropdown value selected validation must be there, if i select TP it may allow null/blank but for other values it must not be blank, how would i achieve this?

mercredi 21 septembre 2016

Credit card numbers starts with 1 & 15 digits long

i have written following jquery/javascript function for validating a credit card which is 15 digit long & must start with digit1. so, how would i validate that the number will start with digit 1.

if ($("#ddlCreditCardType" + i).val() == 'VI') {
  if (!($("#txtCreditCardNo" + i).val().length == 16)) {
    $("#err" + i).html('Credit Card Number should be 16 digit');
    status = 0;
  } else if ($("#txtCreditCardNo" + i).val().substring(0, 3).toLowerCase() == "rnr") {
    $("#err" + i).html('');
    status = 1;
  } else if ($("#txtCreditCardNo" + i).val().substring(0, 1) != 4) {
    $("#err" + i).html('Invalid Credit Card Number');
    status = 0;
  } else {
    $("#err" + i).html('');
    status = 1;
  }

How can I allow both ADFS/STS and Forms authentication in the same application?

I have an application that currently works only with Forms authentication, but now it will be exposed on the internet using HTTPS/SSL and in this case it needs to accept STS/ADFS authentication.

I followed the instructions from this MSDN article: http://ift.tt/2cSJC0I, but how can I set my application to allow both authentication methods?

Web.config settings applied:

<configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://ift.tt/1eigFsq -->

    <section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
    <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>


<location path="FederationMetadata">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>
<authentication mode="None" />

<authorization>
    <deny users="?" />
</authorization>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

        <add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
    </handlers>

    <modules>
        <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" />
        <add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
        <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
    </modules>
</system.webServer>

<system.identityModel>
    <identityConfiguration>
        <audienceUris>
            <add value="https://localhost:44300/Desvio/" />
        </audienceUris>
        <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <trustedIssuers>
                <add thumbprint="‎a527140bc9f440ebd6992ba26c6ea4758c3a2738" name="sts-dev.myserver.com" />
            </trustedIssuers>
        </issuerNameRegistry>
        <certificateValidation certificateValidationMode="None" />
    </identityConfiguration>
</system.identityModel>
<system.identityModel.services>
    <federationConfiguration>
        <cookieHandler requireSsl="false" />
        <wsFederation passiveRedirectEnabled="true" issuer="http://ift.tt/2dkP6E6" 
                    realm="https://localhost:44300/Desvio/" reply="https://localhost:44300/Desvio/" requireHttps="true" />
    </federationConfiguration>
</system.identityModel.services>

Model Validations in Tool Tip in MVC - aspx engine

I need to change the hard coded validation "Agent Name is Required" to Dynamic. This validation should be pulled from model.

I am displaying the hardcoded value in a Tool tip. Want to display multiple messages from Model as Email invalid Format and Email Required

  <div class="form-group">
    <label class="control-label"><%:Resources.Labels.IAName%></label>
    <i class="glyphicon glyphicon-asterisk glyphicon-required"></i>
    <%= Html.TextBoxFor(m =>  m.IAName, new {title="Agent Name is Required", @class ="IALoanInfo", maxlength="50"}) %>
  </div>

    $('.IALoanInfo').tooltip();
    $(function () {
        $('.IALoanInfo').on('shown.bs.tooltip', function () {
            $('.tooltip').addClass('animated fadeInUp');
        })
    })

Model

    [Required(ErrorMessageResourceName = "EmailAddressRequiredError", ErrorMessageResourceType = typeof(Resources.Labels))]
    [DataType(DataType.EmailAddress, ErrorMessage = "EmailAddressRequired")]
    [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Invalid Email-Address")]
    public string InsuranceAgentEmail { get; set; }  

ASP.NET MVC 3: Remove “name” attribute in TextBoxFor

Is it possible to remove the name attribute generated by Html.TextBoxFor?

The following

@Html.TextBoxFor(x => x.SomeName, new
{
    @class = "some-class",
    @autocomplete = "off",
})

outputs

<input autocomplete="off" class="some-class" id="SomeName" name="SomeName" type="text" value="some value">

I want to be able to generate this HTML though:

<input autocomplete="off" class="some-class" id="SomeName" type="text" value="some value">

lundi 19 septembre 2016

How do I delete an item from my database that has two primary keys in asp.net MVC?

Hi guys I recently started getting into asp.net and I am still new to it. I have been working on a project and have hit a wall. Let me first give you some details on my project. I am trying to create a scheduling system with few features one of them being able to add other existing users who has registered as "contacts" with which you can share tasks with.

The user does this by searching for an email of an existing user and if it exist they can add that user as a contact.

Now here is my problem. The adding of a contact and everything works fine however I am having trouble with deleting them. In the index view for the delete action link, I tried both using ContactUserId and ApplicationUserId only to realize that this wont work since it is a association class and has two primary keys. My friend who is very reluctant to help me suggested I should bind the two primary keys but I have no idea how to go about this. Please and thank you for any help.

Controller:

[Authorize]
public class ContactsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Contacts
    public ActionResult Index()
    {

        IEnumerable<ApplicationUser> users = db.Users.ToList();

        IEnumerable<Contact> contacts = db.Contacts.ToList().Where(c =>     c.ApplicationUserID.Equals(User.Identity.Name));

        List<ApplicationUser> curUsers = new List<ApplicationUser>();

        foreach (var contact in contacts)
        {
            foreach (var user in users)
            {
                if (contact.ContactUserID.Equals(user.UserName))
                {
                    curUsers.Add(user);
                }
            }
        }

        ContactsViewModel cvm = new ContactsViewModel();
        cvm.users = curUsers;
        cvm.contacts = contacts;

        return View(cvm);
    }

    // GET: Contacts/Details/5
    public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // GET: Contacts/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Contacts/Create
    // To protect from overposting attacks, please enable the specific     properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include =     "ApplicationUserID,ContactUserID,Date")] Contact contact)
    {
        if (!String.IsNullOrWhiteSpace(contact.ContactUserID))
        {

            var count = db.Users.Count(u => u.UserName == contact.ContactUserID);

            if (count != 0)
            {
                contact.ApplicationUserID = User.Identity.Name;
                contact.Date = DateTime.Today; 
                db.Contacts.Add(contact);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //User already exist error message                        
        }

        return View(contact);
    }

    // GET: Contacts/Edit/5
    public ActionResult Edit(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ApplicationUserID,ContactUserID,Date")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            db.Entry(contact).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(contact);
    }

    // GET: Contacts/Delete/5
    public ActionResult Delete(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(string id)
    {
        Contact contact = db.Contacts.Find(id);
        db.Contacts.Remove(contact);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

Model:

    public class Contact
{
    [Key]
    [Column(Order = 0)]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ApplicationUserID { get; set; }

    [Key]
    [Column(Order = 1)]
    [Display(Name = "Contact Email")]
    [Required (ErrorMessage = "Contact email is required")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ContactUserID { get; set; }

    public DateTime Date { get; set; }
}

Index View:

@model MySchedule.ViewModels.ContactsViewModel

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Add", "Create")
</p>
<table class="table">
<tr>
    <th>
        <!--@@Html.DisplayNameFor(model => model.Date)-->
        First Name
    </th>
    <th>
        Last Name
    </th>
    <th>
        Email Name
    </th>
    <th></th>
</tr>
@{
var users = Model.users;
@foreach (var item in users)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("D", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("X", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}
}
</table>

ViewModel:

 public class ContactsViewModel
{
    public IEnumerable<ApplicationUser> users { get; set; }
    public IEnumerable<Contact> contacts { get; set; }

}

vendredi 16 septembre 2016

Is it a good idea to get into CRM domain after working as a ASP.NET MVC developer?

I have been working as a asp.net mvc developer for more than one year in insurance domain company.Now that I have got an offer from a company which is in Microsoft CRM domain,will it be recommendable to get started with it.

Model is null on postback in ajax loaded partial view

I'm using the following pattern http://ift.tt/L1fUzz to load partial views through ajax.

View:

    @using(Html.BeginUmbracoForm("PostContactInformation", "JoiningSurface", null, new Dictionary<string, object> { { "class", "joinform" } })) {
        @Html.AntiForgeryToken()
        <div data-append="@Url.Action("RenderJoiningContactInformation", "JoiningSurface", new { ContentId = CurrentPage.Id })"></div>
    }

With Action:

 public ActionResult RenderContactInformation(int ContentId)
       {
            var viewModel = ContactViewModel();
            viewModel.Content = Umbraco.TypedContent(ContentId);

            return PartialView("RenderContactInformation", viewModel);
        }

Loads partial view perfectly.

// No need to add partial view i think

Post action works correctly as well:

public ActionResult PostContactInformation(ContactViewModel model)  
{
//code here
    return RedirectToUmbracoPage(pageid);
}

The problem is, that i need to add model error to CurrentUmbracoPage if it exists in post...

For example:

public ActionResult PostContactInformation(ContactViewModel model)  
{
    ModelState.AddModelError(string.Empty, "Error occurred");
    return CurrentUmbracoPage();
}

In this case i get null values for current model. And this happens only when i use ajax.

If i load action synchronously like that:

   @using(Html.BeginUmbracoForm("PostJoiningContactInformation", "JoiningSurface", null, new Dictionary<string, object> { { "class", "joinform" } })) {
                @Html.AntiForgeryToken()
                @Html.Action("RenderContactInformation", "JoiningSurface", new { ContentId = CurrentPage.Id })
            }

everything works like it should.

But i need to use ajax. Is there a correct way to pass values on postback in this case? I know that i can use TempData, but i'm not sure that this is the best approach. Thanks for your patience

I am adding a dll to VS whose name is MVCPageing

I wanted to do some work in Pageing. I added up ddl mvcpageing add refrence--> and browse and added up successfully.Now when i try to write.

Using using MvcPaging .. and its now adding up now

jeudi 15 septembre 2016

Service Unavailable HTTP error 503 when browsed from IIS 7

Recently I have changed my credentials and made similar credential changes in Advanced settings of Application pools of IIS. I have configured DefaultAppPool correctly. When I browsed from IIS, I am getting Service Unavailable 503 error. Please, help me to resolve this issue. I have already gone through previous posts Getting "Service Unavailable" error when browsing IIS website, IIS 7 Service Unavailable 503 ERROR. But, they are not worth to resolve my issue.

mercredi 14 septembre 2016

What is Scaffold in ASP.Net MVC?

I started studying ASP.Net MVC e read about Scaffolf but I could not really understand what is it.

1- What is it?

2-Why would I use it in ASP.Net MVC?

mardi 13 septembre 2016

Is there a plug.ins or code for notification in JS just like in Facebook?

I'm developing an asp.net mvc3 project. I am planning to do like the FB Notification/s. Is there any plug.ins to do like that or a JS code?. Just like the latest FB when using a google chrome every notification/s or message will promt in lower right of the screen if the user FB is log.in. Is my idea possible if it is possible share an idea please if not then I won't continue my idea. Thanks

For the tags I'm just following the suggested tags.

how to get the value from Enum in HtmlHelper.dropdown mvc?

I write an Enum for months of year that my enum use resourse type for multi language

public enum MonthType : byte
    {
        [Display(ResourceType = typeof(Global.Caption), Name = "FirstMonth")]
        FirstMonth = 1,
        [Display(ResourceType = typeof(Global.Caption), Name = "SecoundMonth")]
        SecoundMonth = 2,
        [Display(ResourceType = typeof(Global.Caption), Name = "ThirdMonth")]
        ThirdMonth = 3,
        [Display(ResourceType = typeof(Global.Caption), Name = "ForthMonth")]
        ForthMonth = 4,
        [Display(ResourceType = typeof(Global.Caption), Name = "FifthMonth")]
        FifthMonth = 5,
        [Display(ResourceType = typeof(Global.Caption), Name = "SixthMonth")]
        SixthMonth = 6,
        [Display(ResourceType = typeof(Global.Caption), Name = "SeventhMonth")]
        SeventhMonth = 7,
        [Display(ResourceType = typeof(Global.Caption), Name = "EighthMonth")]
        EighthMonth = 8,
        [Display(ResourceType = typeof(Global.Caption), Name = "NinthMonth")]
        NinthMonth = 9,
        [Display(ResourceType = typeof(Global.Caption), Name = "TenthMonth")]
        TenthMonth = 10,
        [Display(ResourceType = typeof(Global.Caption), Name = "EleventhMonth")]
        EleventhMonth = 11,
        [Display(ResourceType = typeof(Global.Caption), Name = "TwelfthMonth")]
        TwelfthMonth = 12
    }

and i Used in my HtmlHelper.dropDownlist:

<div class="form-group">
                @Html.LabelFor(model => model.YearOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.MonthOfBirth, new SelectList(Enum.GetValues(typeof(Shared.Entities.SMP.Enum.MonthType)))           )
                    @Html.ValidationMessageFor(model => model.YearOfBirth, "", new { @class = "text-danger" })
                </div>
            </div>

in RunTime i see just Enum's List with Resourse Type

dimanche 11 septembre 2016

how to check null in javaScript function?

I want to check null and empty id in JavaScript function,but if syntax isn't work ?

var id = "<%=Request["Id"]%>";
 if (id !== "")
 if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
 window.location = "/Controller/Action.aspx?Id=" + id; }

samedi 10 septembre 2016

Pass formdata from view as ExpandoObject to controller?

View:

Controller: public IActionResult Pass(System.Dynamic.ExpandoObject person) {...}

However it only passes the propertyname of firstname and not its textbox value....?

vendredi 9 septembre 2016

Convert different types of objects and list in Datatable C#

I am new to Data Components in C# and I aa trying to convert 2 different objects and 1 list object in datatable but not able to do so.

My two objects are p_avail

pna_response.PriceAndAvailability p_avail = new pna_response.PriceAndAvailability();

p_avail object has following member variables: name, quantity price, branch(list type)

header_details object has following member variables: senderid, recieverid, date

list_branch contains the object of type branch where branch has member variables called orderdate, ordered, location

Other object is header_details

 pna_response.TransactionHeader header_details = new pna_response.TransactionHeader();

List object is list_branch

List<pna_response.Branch> list_branch = new List<pna_response.Branch>();

Now I want to convert all of the above objects in datatable to display data from any of data component

mardi 6 septembre 2016

Why my code can't locate the data table?

I have this code below to generate a report. My problem is why one of the content of my data table can't locate by my code?. The ds.dt_ProposedSeminars is the table.

public JsonResult ReportProposal(int year)
     {
         string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg  ";
         string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g  ";

         JsonResult result = new JsonResult();
         MemoryStream oStream;

         PCSO_ProposedSeminars rpt = new PCSO_ProposedSeminars();
         dsPCSO_TrainingProgram ds = new dsPCSO_TrainingProgram();

         //-----------------------------------------------------
         var seminars = db.Certificates
            .Where(x => x.Year.Value.Year == year && !x.IsApproved.HasValue)
            .Select(z => z).Distinct();

         foreach (var train in seminars)
         {
             string trainingProgram = train.CertificateName;
             string resourcePerson = train.ResourceSpeaker;
             string target = "";

             var classifications = db.CertificateTrainingClassifications.Where(a => a.CertificateId == train.CertificateId).Select(b=>b.TrainingClassification.Classification);

             int x = 1;
             foreach (var classification in classifications)
             {
                 if (classifications.Count() > 1)
                 {
                     if (x == 1) target += classification;
                     else target +=  ", " + classification;
                 }
                 else target += classification;

                 x++;
             }

             if (train.TargetParticipants.HasValue)
             {
                 target += "/" + train.TargetParticipants.Value + ((train.TargetParticipants != null) ? " pax" : "");
             }

             if (train.IsPerBatch.Value)
             {
                 target += "/batch";
             }
             string duration = train.Duration.Value + " days";
             decimal estimatedExpenses = new decimal();
             estimatedExpenses = train.EstimatedExpenses.Value;
             ds.dt_ProposedSeminars.Adddt_ProposedSeminarsRow(
                     trainingProgram,
                     resourcePerson,
                     target,
                     duration,
                     estimatedExpenses);
         }

         DataTable dtable = new DataTable();
         dtable = ds.dt_ProposedSeminars;
         rpt.SetDataSource(dtable);
         rpt.Refresh();
         rpt.SetParameterValue(0, year);
         rpt.SetParameterValue(1, "");
         rpt.SetParameterValue(2, "Head, Training Unit, Admin Department");
         oStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
         string filename = Convert.ToString((DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Millisecond)) + "RequestApplication";
         var len = oStream.Length;

         FileTransferServiceClient client2 = new FileTransferServiceClient();
         RemoteFileInfo rmi = new RemoteFileInfo();
         DateTime dt = DateTime.Now;
        DownloadRequest dr = new DownloadRequest();
         string fId = client2.UploadFileGetId("", filename, len, PassKey, Userkey, oStream);
         result.Data = new
         {
             fileId = fId,
             filename = filename
         };
         rpt.Close();
         rpt.Dispose();
         oStream.Close();
         oStream.Dispose();
         result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
         return result;
     }

Here is the picture.

Here is the error.

lundi 5 septembre 2016

Error [$injector:unpr] when injecting sanitize dependency

I am trying to use progressBar from AngularUIBootstrap.

I have a objectFactory.js file:

(function () {
    var objectiveFactory = function ($http, animate) {
        debugger;
        return {
            getObjectives: function () {                
                return $http.get('/api/Objective/');
            }
        };

    };
    debugger;
    try {
        //objectiveFactory.$inject = ['$http', '$animate', '$sanitize'];// error
        objectiveFactory.$inject = ['$http', '$animate'];// no error
        angular.module('app', []).factory('objectiveFactory', objectiveFactory);
    }
    catch (e)
    {}    
}());

It is really weird, however if I add new dependency $sanitize:

objectiveFactory.$inject = ['$http', '$animate', '$sanitize'];// not working

Then I've got an error:

angular.js:13920 Error: [$injector:unpr] http://ift.tt/2cintt2$injector/unpr?p0=sanitizeProvider%20%3C-%20sanitize%20%3C-%20objectiveController at Error (native) at http://localhost:15533/Scripts/angular.min.js:6:412 at http://localhost:15533/Scripts/angular.min.js:43:174 at Object.d [as get]

But '$http' and '$animate',injections perfectly works.

I've explored a lot of info and double checked the following advices in my Web API application:

  1. I've checked versions angular'js file and angular-sanitize.js and they are the same 1.5.8.

  2. My bundle files look like this:

     bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
                 "~/Scripts/jquery-1.10.2.min.js",
                 "~/Scripts/bootstrap.min.js",
                 "~/Scripts/angular.min.js",                     
                 "~/Scripts/angular-animate.min.js",
                 "~/Scripts/angular-sanitize.min.js",
                 "~/Scripts/ui-bootstrap-tpls-2.1.3.js",  
                 "~/Scripts/objectiveFactory.js",
                 "~/Scripts/objective.js"
    
                 ));
    
    
  3. I've tried various ways of injection:

    objectiveController.$inject = ['$scope', '$http', 'objectiveFactory', '$animate', 'ngSanitize'];
    objectiveController.$inject = ['$scope', '$http', 'objectiveFactory', '$animate', '$sanitize'];
    objectiveController.$inject = ['$scope', '$http', 'objectiveFactory', '$animate', 'sanitize'];
    
    

However, the error is the same:

angular.js:13920 Error: [$injector:unpr] Unknown provider:

Does anybody know what I've done wrong? ('$http'injection perfectly works)

How is the input elements value persists in MVC after a postback?

i am new to MVC and i have a question in mind. Http is a stateless protocol and we maintain state in asp.net using State Management technique. My question is how does MVC handles to persist the value of an element after a postback. Example: I have a controller like this

public class LoginController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Validate(Cred obj)
        {
            if (obj.UserName == "A" && obj.Password == "A")
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View("Index");
            }
        }
    }

and a view like this

 @using (Html.BeginForm("Validate", "Login"))
        {
            <fieldset>
                <div>
                    UserName:@Html.TextBox("userName")
                </div>
            </fieldset>
            <fieldset>
                <div>
                    Password:@Html.TextBox("password")
                </div>
            </fieldset>
            <input type="submit" value="Submit" />
        }

whenever my page fails to get validate i redirect to my index page and the value in the textbox remains unchanged. How is this managed in MVC. Thank you

samedi 3 septembre 2016

Passing a JSON object to a controller

I'm new to MVC and JavaScript, and while this may be an obvious answer for some I've been struggling for a while now (after looking at many examples)!

When debugging through the Index.cshtml view, the newData object hasn't been populated by the textboxes (set up in a partial view called AddNewProduct.cshtml). The partial view is displayed by clicking a button set within Index.cshtml (this works fine). I can see that the newProduct object in my controller has not been filled due to the problem in the view.

My main question is how do I get the values from my textboxes into the newData object?

Any suggestions would be greatly appreciated! Thank you.

HomeController.cs:

[HttpPost]
        public PartialViewResult RunAddNewProduct(Product newProduct)
        {
                SqlConnection con = new SqlConnection();
                con.ConnectionString = Connections.connection;
                con.Open();

                using (con)
                {
                    SqlCommand cmd = new SqlCommand("INSERT INTO Product VALUES(@Id, @Name, @Description, @Price, @UnitsInStock)", con);

                    cmd.Parameters.Add(new SqlParameter("@Id", newProduct.Id));
                    cmd.Parameters.Add(new SqlParameter("@Name", newProduct.Name));
                    cmd.Parameters.Add(new SqlParameter("@Description", newProduct.Description));
                    cmd.Parameters.Add(new SqlParameter("@Price", newProduct.Price));
                    cmd.Parameters.Add(new SqlParameter("@UnitsInStock", newProduct.UnitsInStock));

                    SqlDataReader rd = cmd.ExecuteReader();

                    while (rd.Read())
                    {
                        newProduct.Id = Convert.ToInt32(rd.GetInt32(0));
                        newProduct.Name = Convert.ToString(rd.GetSqlValue(1));
                        newProduct.Description = Convert.ToString(rd.GetSqlValue(2));
                        newProduct.Price = Convert.ToDecimal(rd.GetDecimal(3));
                        newProduct.UnitsInStock = Convert.ToInt32(rd.GetInt32(4));
                    }
                }
                return PartialView("AddNewProduct", newProduct);           
        } 

Index.cshtml:

$('#btnConfirmNewProduct').live('click', function () {

        var newData = {
                'id': $('#txtId').val(),
                'name': $('#txtName').val(),
                'description': $('#txtDesc').val(),
                'price': $('#txtPrice').val(),
                'unitsInStock': $('#txtUnitsInStock').val()
        };

        $.ajax({
            url: '/Home/RunAddNewProduct',
            data: JSON.stringify(newData),
            type: 'POST',
            dataType: 'json'
        })
            .success(function (result) {
                $('#products').html(result);
            })
            .error(function (xhr, status) {
                alert(status);
            })
    });

AddNewProduct.cshtml:

<table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th>Units In Stock</th>
        </tr>
        <tr>
            <td><input id="txtAddId" type="text"/></td>
            <td><input id="txtAddName" type="text"/></td>
            <td><input id="txtAddDesc" type="text"/></td>
            <td><input id="txtAddPrice" type="text"/></td>
            <td><input id="txtAddUnitsOfStock" type="text"/></td>
        </tr>
    </table>
    <input id="btnConfirmNewProduct" type="button" value="Confirm New Product" />

vendredi 2 septembre 2016

Return object where validation failed on DataMember

I have a DataContract class that looks something like

[DataContract]
public class Foo
{
    [DataMember(Name = "id)]
    [Required]
    public string Id { get; set; }
}

I have a class that represents error responses as

[DataContract]
public class ErrorResponse
{
    [DataMember(Name = "code")]
    [Required]
    public int Code { get; set; }

    [DataMember(Name = "message")]
    [Required]
    public string Message { get; set; }
}

What I want to do is return an instance of the ErrorModel class if the validation on id fails (in this case, if it was not specified.

Is there some attribute I can use to achieve this? Something like

[Required(new ErrorResponse { Code = 1, Message = "id field is required })]

StackOverflow exception for siblings in Umbraco 7.5.2

I have the following structure in Content page

Index
   |__ Blog 1
   |__ Blog 2
   |__ Blog 3
Shared
   |__ Footer
   |__ Icons

In my model which is derived from RenderModel, I have the following code which retrieves footer info from Shared node:

IPublishedContent index = Content.AncestorOrSelf(1); // it gives me Index

IPublishedContent shared = index.FollowingSibling("shared") ??
                           index.PrecedingSibling("shared"); // I don't base on Shared position because it might be after or before Index so I would use ?? operator

IPublishedContent footer = shared?.Descendant("footer");

The problem is that shared variable throws System.StackOverflowException

Why ? Where is my mistake ?

I tried also only:

IPublishedContent shared = index.FollowingSibling("shared") ;

same thing, same exception !

A required anti-forgery token was not supplied or invalid when run from localhost

We have an application which includes anti forgery token and works fine when hosted them on web farms. We are now newly hosting our application in to another servers. When we try to run the same application in the new server as localhost we are getting anti-forgery token error.

Application setup and configuration are same in both the servers. but still I get this issue. I am getting RequestVerificationToken in the web form as well as in cookie too. We have machinekey included in web.config file with SHA1 validation and AES decryption.

Can anyone suggest whey are we getting this issue

jeudi 1 septembre 2016

How to put a value in dropdown using records from database

I want to put a value from database because my dropdown already have a value the same as the text so I want a separate or different value from my text. Example code = 1, text = pathologist.

My controller:

    public ActionResult MainHistopathologyForm(string id)
    {
        var patientprofileViewModel = new MDHPIStables();
        patientprofileViewModel.histopathology = db.histopathology.Find(id);
        patientprofileViewModel.roles = db.roles.Find(Session["role"]);
        var PathologistList = new List<string>();

        var PathologistQry = from d in db.pathologist
                       select d.pathologist;

        PathologistList.AddRange(PathologistQry.Distinct());
        TempData["pathologistlist"] = new SelectList(PathologistList);

        return View(patientprofileViewModel);
    }

MainHistopathologyForm.cshtml:

 @Html.Partial("RolesHistopathologyForm", Model.roles, new ViewDataDictionary())


@Html.Partial("Partial_HistopathologyForm", Model.histopathology,
 new ViewDataDictionary())

Partial_HistopathologyForm:

    @{
        ViewBag.concurring1 = TempData["pathologistlist"];
     }                            
    @Html.DropDownList("concurring1", "Select Pathologist")  

Parameter name: Internal Error: The instance of the MessageContract cannot be null in

I am using a jqgrid 4.3.3. I have this code for my jqgrid below

function ExaminationDocumentGridList(ExaminationId) {
    var url1 = '../PIMSRecords/GetExamDocument?ExaminationId=' + ExaminationId;
    $("#PersonExaminationDocList").jqGrid({
        url: url1,
        datatype: 'json',
        mtype: 'POST',
        colNames: ['RowId', 'sId', 'pID', 'Document Name', 'Document No', 'Validated By', 'Validated Date', '', '', ''],
        colModel: [
              { name: 'rowId', index: 'rowId', hidden: true, width: 65 },
              { name: 'PersonExamDocId', index: 'PersonExamDocId', hidden: true, width: 20, align: 'left' },
              { name: 'ExaminationId', index: 'ExaminationId', hidden: true, width: 65 },
              { name: 'PersonExamName', index: 'PersonExamName', width: 150, align: 'left' },
              { name: 'PersonExamNo', index: 'PersonExamNo', width: 90, align: 'center' },
              { name: 'ValidatedBy', index: 'ValidatedBy', width: 150, align: 'center' },
              { name: 'ValidatedDate', index: 'ValidatedDate', sortable: false, width: 100, align: 'center' },
              { name: 'fileextension', index: 'fileextension', hidden: true, sortable: false, width: 70, align: 'center' },
              { name: 'ImageReportId', index: 'ImageReportId', hidden: true, sortable: false, width: 70, align: 'center' },
              { name: 'ImageFileName', index: 'ImageFileName', hidden: true, sortable: false, width: 70, align: 'center' }
              ],
        pager: $('#PersonExaminationDocPager'),
        rowNum: 3,
        rowList: [3, 6, 12],
        sortname: 'ValidatedDate',
        sortorder: "desc",
        viewrecords: true,
        height: '100%',
        onSelectRow: function (id) {
            var objRowData = jQuery("#PersonExaminationDocList").getRowData(id);
            var PersonExamName = objRowData.PersonExamName;
            var PersonExamNo = objRowData.PersonExamNo;
            var ValidatedBy = objRowData.ValidatedBy;
            var ValidatedDate = objRowData.ValidatedDate;

            var docid = objRowData.ImageReportId;
            var docname = objRowData.ImageFileName;
            var fileextension = objRowData.fileextension;
            $("#hidExamDocImageReportId").val(docid);
            $("#hidExamDocImageFileName").val(docname);

            $("#PersonExamName").val(PersonExamName);
            $("#PersonExamNo").val(PersonExamNo);
            $("#divSignatoryId #HRHead option:contains(" + ValidatedBy + ")").attr('selected', 'selected');
            $("#ValidatedDate").val(ValidatedDate);
            var url = '../PIMSRecords/_ExaminationDoc/' + objRowData.PersonExamDocId;
            var pId = objRowData.PersonExamDocId;
            $("#hidEntryPersonExamDocId").val(pId);

            viewpartialExamdocs(url, "partialExamDoc");
        },
        loadComplete: function () {
            /*gets the ids of grid */
            var ids = jQuery("#PersonExaminationDocList").getDataIDs();
            /*gets the number of rows of the Grid */
            var len = ids.length, newLine;
            if (len < 3) {
                /*Make a blank newlineData */
                /*Calls the function to add row data */
                AddNewRowToGridLISTOFDOCUMENT(len, '#PersonExaminationDocList');
            }
        }
    });
}

For the function

function viewpartialExamdocs(url, partialDocumentPreview) {
    $.ajax({
        type: "POST",
        url: url,
        data: {},
        success: function (response) {
            $("#" + partialDocumentPreview + "").html(response);
            var fileId = $("#hidExamDocImageReportId").val();
            var filename = $("#hidExamDocImageFileName").val();
            fileextension = filename.substr(filename.lastIndexOf('.') + 1, 4);
            if (fileextension == 'pdf') {
                $("#EmpExamimgFirstPreview").hide();
                $("#EmpExamiFrameFirstPreview").show();
                var varsrc = "../UploadDownload/_ViewPDF?&fId=" + fileId + "&filename=" + filename;
                $("#EmpExamDocFrameId").attr('src', varsrc);
                $("#ExamDocPreviewFrameId").attr('src', varsrc);
            } else {
                $("#EmpExamimgFirstPreview").show();
                $("#EmpExamiFrameFirstPreview").hide();
            }
        },
        error: function (response) {
            alert("error" + response);
        },
        datatype: "html"
    });
}

This is for my controller

[HttpPost]
    public ActionResult _ExaminationDoc(int id)
    {
        ViewData["ExaminationDoc"] = _or.GetPersonExamDoc(id);
        return PartialView("_ExaminationDoc", ViewData["ExaminationDoc"]);
    }

Here for my the data where my controller get

public PersonExaminationDocument GetPersonExamDoc(int id)
    {
        var examdoc = (from ed in db.PersonExaminationDocuments
                       where ed.PersonExamDocId == id
                    select ed).SingleOrDefault();
        return examdoc;

    }

This code is for viewing the picture

    @model PIMS.Models.PersonExaminationDocument
<center>
    <fieldset style="width: 160px; height: 250px">
        <legend style="text-align: left; font-style: normal; font-weight: bold; font-family: Arial;
            font-size: 12px;">Document Preview</legend>
        <div id="EmpExamimgFirstPreview">
            @if (Model != null)
            {
                if (Model.ImageReportId != null)
                {
                <img  alt="ExamDoc" id="ExamDocimg"  height="220px" width="150px" src="@Url.Action("Download", "UploadDownload", new { @id = Model.ImageReportId, @fname = Model.ImageFileName })" />                                                           
                }
                else
                {
                <img  alt="ExamDoc" id="ExamDocimg"  height="220px" width="150px" src="@Url.Content("~/Content/Images/document_preview.png")"/> 
                }
            }
            else
            {
                <img  alt="ExamDoc" id="ExamDocimg"  height="220px" width="150px" src="@Url.Content("~/Content/Images/document_preview.png")"/> 
            }
        </div>
        <div id="EmpExamiFrameFirstPreview" runat="server" style="display: none">
            <iframe id="EmpExamDocFrameId" style="width: 150px; height: 220px;"></iframe>
        </div>
    </fieldset>
</center>
<input id="hidImageId" type="hidden" />
<input id="hidFNameId" type="hidden" />
<input id="hidExamuploadedDoc" type="hidden" />
<input id="hidExamDocsExtensionid" type="hidden" />

This is the code to download the picture for viewing and my error

public ActionResult Download(Guid id, string fname)
    {           
        FileTransferServiceClient client = new FileTransferServiceClient();
        DownloadRequest dr = new DownloadRequest();         
        RemoteFileInfo rmi = new RemoteFileInfo();            
        Stream stream = null;

        string pId = id.ToString();
        string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg";
        string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g";          
        client.Open();          
        rmi = client.DownloadFile(ref pId, ref fname, ref PassKey, ref  Userkey);  -------- Here is where i get my error why?
        stream = rmi.FileByteStream;         
        MemoryStream writeStream = new MemoryStream();
        Int32 chunksize = 2048;         
        Byte[] buffer = new Byte[chunksize];          
        do
        {
            Int32 bytesRead = stream.Read(buffer, 0, chunksize);
            if (bytesRead == 0)
            {
                break;
            }
            writeStream.Write(buffer, 0, bytesRead);
        } while (true);
        client.Close();       
        string ext1 = Getextension(fname);
        string ext = ext1.ToLower();
        string contentType = "image/png";          
        if ((ext == "jpeg") || (ext == "png"))
        {
            contentType = "image/png";
        }
        else if ((ext == "gif"))
        {
            contentType = "image/gif";
        }
        else if (ext == "txt")
        {
            contentType = "text/html";
        }
        else if ((ext == "doc") || (ext == "docx"))
        {
            contentType = "application/msword";
        }
        else if ((ext == "ppt") || (ext == "pptx"))
        {
            contentType = "application/vnd.ms-powerpoint";
        }
        else if (ext == "pdf")
        {
            contentType = "application/pdf";
        }
        else if ((ext == "mp3"))
        {
            contentType = "audio/mpeg";
        }
        else if (ext == "mp4")
        {
            contentType = "video/mp4";
        }
        else if (ext == "flv")
        {
            contentType = "video/x-flv";
        }
        else if (ext == "wmv")
        {
            contentType = "application/x-ms-wmv";
        }
        var imageBytes = writeStream.ToArray();

        if (imageBytes == null)
        {
            return new FilePathResult("~/Content/Images/btn_mtops_pic.png", "image/png");
        }
        else
        {
            FileContentResult file = new FileContentResult(imageBytes, contentType);
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fname);
            return file;
        }
    }

And also i got this for my TFS http://ift.tt/2bGv0Pm

This is the error i get. Anyone know about this?. Please Help. Thanks.

Updating windows/view automatically after data is saved in another window/view

I should update a table in a view automatically, after data is saved in another view.

I looked this "updating data automatically in another view", but the solution was something about angular.

How, if I can, make this update with ASP.NET MVC3 and Jquery (just learning this).

It is possible to get the mac address of a PC using a click button?

I don't know if my title is possible or not. But is there any way how to get or determine the mac address of a PC?. If it is possible to determine the mac address in what way?. As my title above the scenario is after he/she click a certain button the mac address will save to sql server database or display to a label. I'm trying to do this in a project I am working at asp.net mvc3 I didn't try anything yet because I don't know where and how to start. Thanks.