vendredi 29 juillet 2016

Is there any way to exclude a property call on mvc

Is there any way to call the properties of a view model in a conditional way Here is my view model , where the Prooperty DataPack actually calls a webservice which is another component in our project . I dont need to call this DataPack service call when the Casename is X .

public class TypeSelectorViewModel
{
    public TypeSelectorViewModel();

    public string caseID { get; set; }
    public bool CaseName { get; set; }
    public string DataPack{ get; set; }
}

In my controller whenever a new instance of TypeSelectorViewModel creates it actually calling the DataPack webservice call and it is taking too much time to execute. This i cant remove because this call is required in some condition and some condition i want to exclude the service call . Is there any way to handle it in MVC.

This is observed as a performance issue on live environment .

ASP.Net MVC customize Attribute to replace the same code

In about half of my Action in ASP.Net MVC, I need to repeat some code like try catch the whole Action or change the http response header. I don't want to copy and paste the same code. How can I write a customize attribute to help me add this code?

Filtering with multiple Parameters when using PagedList - MVC

I create a page with sorting, filtering,paging(use PagedList) follow this tuts : Link here

I have a question : If i filter with multi params : My Filter

So how can i send this data to Action ?

"String was not recognized as a valid DateTime" by getting a value of date from JS

I have this code to retrieve a date

var _Sdate = new Date(Date.parse($("#LSDate").val()));

It been loop thats why I got 2 dates.

Result for day

And now I am getting this error:

Error.

I have tried to set DateTime date1 but I got also an error.

jeudi 28 juillet 2016

Why is lambda syntax needed in a c# foreach statements in the view?

So if you utilize Visual Studio's scaffolding for an MVC project, you will get this:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
    </tr>
}

What is the difference, however, between that and this:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(item.Name)
        </td>
    </tr>
}

(the lambda statement has been removed in the second example)


How are these two different? Can someone help me to understand the difference here?

I had read that using Lambda allows "property info" to be sent to the DisplayFor method, but am not sure what this is or what value it offers.

Why is lambda notation even needed in Razor?

I think my understanding of lambda notation is lacking because I do not understand why it is even needed in Razor. For example:

instead of this:

@Html.DisplayFor(modelItem => item.FirstName)

why can't we just have this:

@Html.DisplayFor(item.FirstName)

What is the purpose of the lambda syntax and why do we need to add in all of the extra work of typing out the lambda notation?

Can someone help me to understand why this is needed and what benefit it offers?

Partial view doesn't refresh data table - MVC

I have a Action as :

public async Task<ActionResult> SearchProduct(SearchModel search , int? page)
{
    . . . Get data . . . .

    var pageSize = 4;
    int pageNumber=(page ?? 1);
    return PartialView(data.ToPagedList(pageNumber,pageSize));
}

Partial view of SearchPorduct :

//show data from Action SearchProduct

SearchModel :

public class SearchProduct
{
   public string ProductCode {set;get;}
   public string Price {set;get;}
   public DateTime? from{set;get;}
   public DateTime? to{set;get}
}

I have a another Action with Partial view as a filter. It has 4 and 2 button :

<input type="text" placeholder="ProductCode"/>
<input type="text" placeholder="Price"/>
<input type="text" placeholder="Prom"/>
<input type="text" placeholder="To"/>
<button>Send</button>
<button>Clear</button>

when i click button "Send", i call ajax post to Action "SearchProduct" and refersh data in it's partial view. But it's not working !

How to refresh data of partial view each click button "Send"?

Redirect to index method of any controller using anchor tag asp.net mvc

i want to redirect to index action method of Zone Controller,but i receive an error, The resource you are looking for (or one of its dependencies) could have been removed, had its name changed.

<a href="/Zones/"><span class="glyphicons glyphicons-inbox"></span> Zones</a>

hiddden-xs hiding div on print in Bootstrap

In MVC project, we are using bootstrap.

There is need to hide div for xs devices and have to show at time of print and desktop.

Code is in below as:

--Content--

But it is hiding div at time printing to window.

Redirect to index action method of any controller asp.net mvc

I want to redirect to index action method of Zone Controller,but i receive an error, The resource you are looking for (or one of its dependencies) could have been removed, had its name changed

<a href="/Zones/"><span class="glyphicons glyphicons-inbox"></span> Zones</a>

mercredi 27 juillet 2016

How to add the checked check boxes from JQgrid to database?

I have this code below and I want is to add the checked check boxes that I choose from the my grid into my dabase. Here is my JQgrid code

function HalfDay() {
    var url1 =URL

    $("#List").jqGrid({
        url: url1,
        datatype: 'json',
        mtype: 'POST',
        colNames: ['RowId', 'AM', 'PM', 'Date', 'Day'],
        colModel: [
                { name: 'rowId', index: 'rowId', hidden: true, editable: true, sortable: false, width: 80, align: 'left' },
                 { name: 'PM', index: 'cbox_leave_halfPM', editable: true, formatter: cboxFormatterLeaveHalfDayPM, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
{ name: 'PM', index: 'cbox_leave_halfPM', editable: true, formatter: cboxFormatterLeaveHalfDayPM, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
                { name: 'LStartDate', index: 'LStartDate', editable: false, sortable: false, width: 70, align: 'left' },
                { name: 'LDate', index: 'LDate', editable: false, sortable: false, width: 55, align: 'left' }
          ],
        pager: $('#Pager'),
        rowNum: 5,
        rowList: [5, 10, 20],
        sortname: '',
        sortorder: '',
        viewrecords: true,
        imgpath: '/Content/themes/redmond/images/',
        height: '100%',            
        loadComplete: function (result, rowid) {
            var ids = jQuery("#List").getDataIDs();
            var len = ids.length, newLine;
            if (len < 5) {
                AddNewRowToGrid(len, "#List");
            }
            $("#Pager").css("width", "auto");
            $("#Pager .ui-paging-info").css("display", "none");
        }
    });
    return false;
}

I can't think well enough because of this of problem that I encounter. I tried some codes that I think it is possible but no luck.

Does mapping an .edmx file to Stored Proedures really offer that much of a security advantage? (more inside)

I have mapped entities in an edmx file to stored procedures (SP) in the past for update and insert, along with giving the account only data-reader rights. This allowed the account to read all of the data that is wanted from the database, but forced it to use SPs any time that it needed to write or update.

Upon reflecting on this, however, I am not seeing a huge security advantage to doing this (vs. using no SPs at all). Unless I can prevent someone from updating rows with null or garbage values, there isn't much point, is there?

What do you guys think? Does mapping entity framework to stored procedures offer much of a security advantage?

Is there a list anywhere of all of MVC's data annotations? (e.g. Required, DisplayName, Range)

[DisplayName("Date Released")]
[Required]
etc.

Is there a good reference anywhere that lists all of these data annotations? I keep learning about ones that I didn't know existed.

Routing toactions that have same parameters and different name

I have 2 methods in my controller that have same parameters. Each of them is called on a dropdown selection and then makes a call to their respective REST API using the parameter.

// api/about/{2}
     public ActionResult About(int id)
            {
                ViewBag.Value = id;    
                return View();
            }

//api/contact/{2}
            public ActionResult Contact(int id)
            {
                ViewBag.Value = id;
                return View();
            }

My isssue here is: Whenever I make a dropdown selection, it never reaches method 2. Is there a way I can achieve this?

Html.ValidationMessageFor() not rendering element

I've been using Html.ValidationMessageFor for quite a long time in MVC 3. All of a sudden this extension is no longer working for me, but only in a particular view. The extension is used in a <form> tag and the page has the jquery.validate.min.js and jquery.validate.unobtrusive.min.js attached (among others). I've checked other pages of the site, and those views use the same call and the <span> element is generated.

Here is the markup I'm using:

<form id="assistanceRequestDiv" class="form-group js-more-assistance js-hidden">
   <p>@Translation.TextByDomain("Assistance", "need-further-assistance-contact-customer-support")</p>
   <div class="content-block left-text-children">
      <div class="content-block__quarter-column">
         @Html.LabelFor(x => x.AssistanceRequestFirstName)
         @Html.ValidationMessageFor(x => x.AssistanceRequestFirstName)
         @Html.TextBoxFor(x => x.AssistanceRequestFirstName, new {@class = "form-control", required = "required"})
      </div>
      <div class="content-block__quarter-column">
         @Html.LabelFor(x => x.AssistanceRequestLastName)
         @Html.ValidationMessageFor(x => x.AssistanceRequestLastName)
         @Html.TextBoxFor(x => x.AssistanceRequestLastName, new {@class = "form-control", required = "required"})
      </div>
      <div class="content-block__quarter-column">
         @Html.LabelFor(x => x.AssistanceRequestPhoneNumber)
         @Html.ValidationMessageFor(x => x.AssistanceRequestPhoneNumber)
         @Html.TextBoxFor(x => x.AssistanceRequestPhoneNumber, new {@class = "form-control"})
      </div>
      <div class="content-block__quarter-column set-vertical-align-bottom">
         <button id="btnSubmitAssistanceRequest" class="btn btn--primary">@Translation.Text("submit")</button>
      </div>
   </div>
</form>

Data Annotations

    [RequiredLocalized, DisplayNameLocalized("first-name")]
    public string AssistanceRequestFirstName { get; set; }
    [RequiredLocalized, DisplayNameLocalized("last-name")]
    public string AssistanceRequestLastName { get; set; }
    [RequiredLocalized, DisplayNameLocalized("phone-required")]
    [RegularExpressionLocalized(@"(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]‌​)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]‌​|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})", "please-enter-a-valid-10-digit-phone-number", "Assistance")]
    public string AssistanceRequestPhoneNumber { get; set; }

  • RequiredLocalized - Required attribute that returns a custom message. Works in other places of the site.
  • DisplayNameLocalized - DisplayName attribute with custom message. Works in other places.
  • Etc

This form is hidden by default and shown when the user clicks a certain button. Here are the scripts that are attached to the page:

<script src="/Scripts/jquery-1.8.3.min.js"></script> <script src="/Scripts/jquery-ui-1.10.4.custom.min.js"></script> <script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script> <script src="/Scripts/jquery.validate.min.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.min.js"></script> <script src="/Scripts/jquery.validate.extensions.js"></script> <script src="/Scripts/Shared/jQueryGlobalSettings.js"></script>

Using Javascript to return false if there are errors on the page in this format:

$('#btnSubmitAssistanceRequest').click(function (e) {
    var $answer = $('.js-title');
    var $reqFirstName = $('#AssistanceRequestFirstName');
    var $reqLastName = $('#AssistanceRequestLastName');
    var $reqPhoneNumber = $('#AssistanceRequestPhoneNumber');

    // Check for empty fields
    if ($reqFirstName.val().trim() == "") {
        showErrorMessage($reqFirstName, 'First Name is required.');
    } else {
        clearErrorMessage($reqFirstName);
    }
    if ($reqLastName.val().trim() == "") {
        showErrorMessage($reqLastName, 'Last Name is required.');
    } else {
        clearErrorMessage($reqLastName);
    }
    if ($reqPhoneNumber.val().trim() == "") {
        showErrorMessage($reqPhoneNumber, 'Phone Number is required.');
    } else {
        clearErrorMessage($reqPhoneNumber);
    }

    // check if validation errors were thrown
    if ($(".field-validation-error").length) return false;

    $.post('/api/[obfuscated]/[obfuscated]', { answer: $answer.text(), firstName: $reqFirstName.val(), lastName: $reqLastName.val(), phoneNumber: $reqPhoneNumber.val() }, function (data) {
        if (data.success) {
            $('.request-assistance-success').css('display', 'inline');
            $(".feedback-container").slideUp(400);
        } else {
            $('.request-assistance-failure').css('display', 'inline');
            $(".feedback-container").slideUp(400);
        }
    });

    e.preventDefault();
    return true;
});

mardi 26 juillet 2016

How to Change label value on drp selected change event in MVC

I have below code and I want to change label text base on selected role.

For example, If I select Admin then in label Text I need "Admin Name" etc.

I use below code but I is not working.

 <div class="editor-field">
    @Html.DropDownListFor(model => model.RoleID, new SelectList(ViewBag.RoleLsit, "Id", "RoleName"), "Select Category", new { onchange = "SelectedIndexChanged()" })
</div>

<div>        
    @Html.LabelFor(model => model.RoleName)
    @Html.EditorFor(model => model.RoleName)
    @Html.ValidationMessageFor(model => model.RoleName)
</div>


<script type="text/javascript">

function SelectedIndexChanged() {

    var sub = document.getElementsByName("RoleName");
    sub.value = "Selected Role Name";

}

Thanks

Index was outside the bounds of the array - VS 2010

I know this is a duplicate title but I have a different scenario. I'm using this following code and picture below that I'm getting an error and I'm developing an asp.net mvc3 project.

 string[] hDayCount = _halfdayCount.Split(',');

 decimal daysAppliedWHalfday = ndaysApplied;

int cnthalfday = 0;
DateTime HDstartDate = startDate;
DateTime HDendDate = endDate;
while (HDstartDate <= HDendDate)
 {
if (hDayCount[cnthalfday] == "true")
 {
daysAppliedWHalfday = daysAppliedWHalfday - Convert.ToDecimal(.5);
}
 cnthalfday++;
HDstartDate =  HDstartDate.AddDays(1);
}

PICTURE

Anyone know about this?

Edit, Update and insert date in telerik grid using inline editing in mvc

I am trying to insert a new record in which i want to add startdate and enddate, but when i try to do this it gives outofrange error. and can not convert datetime2 to datetime related to entity framework exception.

Here i attach image of UI.

If possible give me reference how to do this.

Editing view of adding datetime

Child actions are not allowed to perform redirect actions - MVC

I have a _layout load menu as :

...
@Html.Action("MenuRole","Menu")
...

in Action MenuRole i check session with Action Filter :

[CheckSession]
[ChildActionOnly]
public ActionResult MenuRole()
{
    ....
    return PartialView("_LoadMenu",menuModel);
//_LoadMenu is partial view to show menurole
}

And in Action Filter :

public class CheckSession : ActionFilterAttribute, IActionFilter
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ctx = filterContext.HttpContext;

            //if Session == null => Login page
            if (ctx.Session["Username"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Login" }));

            }

            base.OnActionExecuting(filterContext);
        }
    }

When session timeout, _layout show error in @Html.Action("MenuRole","Menu") : Child actions are not allowed to perform redirect actions

lundi 25 juillet 2016

The breakpoint will not currently be hit. No symbols have been loaded for this document in JavaScript

I am developing a project using asp.net mvc3. I know this is a duplicate question however I tried some way like this one

Right click on solution --> Properties    
Look under Common Properties --> Startup Project    
Select multiple startup projects    
select Start action on the projects you need to debug.

Goto Project Properties -> Build -> Advanced... In the "Output" section select "full" in Debug Info dropdown

but nothing happen. But for my controllers and repositories are workings but for my Javascript not working. Can't trace well :(

Regex password validation working fine on regex verification sites but not on mine

I have the following Regex code that works fine on regex verification code but not on my website (built with ASP.NET MVC). It validates the length and numeric but not the absence of special characters.

My regex: /^(?=.*[!@@#$&](?=.*[A-Z]))(?=.*[0-9])(?=.*[a-z]).{8,}$/

On my website Toto1234 is considered fine but that does not be the case since it does not contain a special character.

i need to add the one ExpandoObject() object to another ExpandoObject()

i have an requirement where i need to add one ExpandoObject() list to another ExpandoObject() list. For example dynamic list= new new ExpandoObject(); list = JsonConvert.DeserializeObject>(data); dynamic listdata= new ExpandoObject() o/p what i get from list is like a b null c d null e null null null null null null null null null null null

and required o/p is like a b null c d null e null null

here what i have tried to achieve that for(int i=0;i

                    if(c[j]==null)
                    {

                    }
                    else
                    {
                        if (flag == true)
                        {
                            listdata.Add(list[i]);

                        }
                    }
                }
            }

But the Add function is not there for Expandobject.

please suggest me how should i do that.

Is there a difference between the Controller classes in MVC3 and MVC5?

I've created a project using ASP.NET MVC3. I now want to port it to MVC5. As I'm doing so, will I need to change the Controller classes in any specific ways? Are there different conventions or coding requirements between the two versions, or can I just copy and paste the C# code over without changes?

can not get value of TempData[" "] in mvc?

i set a data in TempData[""] in one action which is type of [HttpGet] and want to get this data in [HttpPost].i just set data in that tepmdata variable conditionally.but i can get that tempdata variable in [HttpPost] if the condition in [httpget] is else.but if that condition is true then i get that tempdata variiable as null only.i don't know the reason why i am getting null. this is [httpget] action.and TempData["jobid"] is my variable.

[HttpGet]
    public ActionResult CreateBidFirstStep(string id)
    {
        BiddingFirstStepModel _objBiddingFirstStepModel = new BiddingFirstStepModel();
        _objBiddingFirstStepModel.DepartmentList = new SelectList(_objBiddingFirstStepBDC.GetDepartments(), "DepartmentId", "DepartmentName");
        _objBiddingFirstStepModel.JobTypeList = new SelectList(_objBiddingFirstStepBDC.GetJobtypes(), "JobTypeId", "JobType");
        _objBiddingFirstStepModel.CustomersList = new SelectList(_objBiddingFirstStepBDC.GetCustomers(), "CustomerId", "CustomerName");
        if (id != null)
        {

            _objBiddingFirstStepModel.isedit = true;
            _objBiddingFirstStepModel.jobdata = _objBiddingFirstStepBDC.GetJobDetailById(id);
            TempData["jobid"] = id;
        }
        else
        {
            TempData["jobid"] = "abc";
        }
        _objBiddingFirstStepModel.CustomersList = new SelectList(_objBiddingFirstStepBDC.GetCustomers(), "Id", "CustomerName");
        Logger.Info("Logger is working here");

        return View(_objBiddingFirstStepModel);

    }

this is my [HttpPost] action.

[HttpPost]
    public ActionResult CreateBidFirstStep(BiddingFirstStepModel formdata)
    {
        //-------------To get all departments------------

        formdata.DepartmentList = new SelectList(_objBiddingFirstStepBDC.GetDepartments(), "DepartmentId", "DepartmentName");
        List<SelectListItem> department = new List<SelectListItem>();
        department = formdata.DepartmentList.ToList();

        JobDTO jobdata = new JobDTO();
        DocumentLatestDTO document = new DocumentLatestDTO();

        //---------To insert Job data-----------

        jobdata.JobName = formdata.jobname;
        jobdata.JobType = formdata.jobtype;
        jobdata.JobTypeId = formdata.jobtypeid;
        jobdata.CustomerName = formdata.customerid.ToString();
        jobdata.JobRefence = formdata.jobreference;
        jobdata.Quantity = formdata.quantity;
        jobdata.AreaOfPCB = formdata.area;
        jobdata.NumberOfJoints = formdata.jointsnumber;
        jobdata.Department = formdata.department;
        jobdata.DepartmentId = formdata.departmentid;
        jobdata.Status = false;
        jobdata.JobDescription = formdata.description;
        jobdata.CreatedOn = DateTime.Now;
        jobdata.CompleteOn = formdata.datepickerEndDate;
        jobdata.Tasktypeid = 1;
        string job = (string)TempData["jobid"];
        if (job== "abc")
        {
        jobdata.NewJobId = _objBiddingFirstStepBDC.Addjobdatatoserver(jobdata);
        }
        else
        {
            BiddingDTO biddingobj=new BiddingDTO();
            biddingobj.jobid=TempData["jobid"].ToString();
            jobdata.JobId = TempData["jobid"].ToString();
            _objBiddingFirstStepBDC.Updatejobdatatoserver(jobdata);
            _objBiddingFirstStepBDC.ReviseBidding(biddingobj);
        }
        //---------To get and save uploaded bom---------

        if (formdata.excelbom != null && formdata.excelbom.ContentLength > 0)
        {
            document.JobId = jobdata.NewJobId;
            document.Department = jobdata.Department;
            document.DocumentName = Path.GetFileNameWithoutExtension(formdata.excelbom.FileName);
            document.DocumentExtension = Path.GetExtension(formdata.excelbom.FileName);
            document.Size = formdata.excelbom.ContentLength;
            document.UploadedBy = "Jitender Singh";
            document.UploadedOn = DateTime.Now;
            document.DocumentType = "BOM";

            FolderCreationUtility foldercreation = new FolderCreationUtility();
            foldercreation.CreateFolder(document, department, PathToSaveDocument);

            document.Path = _objBiddingFirstStepBDC.CreateDocumentPath(document);

            formdata.excelbom.SaveAs(Server.MapPath(PathToSaveDocument + document.Path));
        }
        Logger.Info("Logger is working here");
        return RedirectToAction("CreateBidSecondStep");
    }

please help me why i can not get value if i set my id in TempData in HttpGet action.

How to show [Remote] Error in alertbox ()

How can I make sure that my Email field ValidationMessageFor only show the "Remote" error and not Required- Error.

AND Remote Error to appear in a alertbox ()

[Required(ErrorMessage = "Skriv venligst din e-mailadresse")]
[EmailAddress(ErrorMessage = "Ugyldig e-mailadresse")]
[Remote("DoUserExist","Home",ErrorMessage = "E-mail already in use")]
[DataType(DataType.EmailAddress)]
public string Emailaddress{ get; set; }



 @Html.TextBoxFor(model => model.Emailaddress, new { @placeholder = "E-mailadresse" })
 @Html.ValidationMessageFor(model => model.Emailaddress)

samedi 23 juillet 2016

Why customer have to go for MVC instead of Asp.Net

I am just newbie towards the Asp.Net MVC. I have not been so much exposed to Web technology too.

I have seen some advantage of MVC over the classic Asp.Net...

But I had a question after some months.

What is in it for the customer.... Is there any reason, that I can convince the customer/client to go for the MVC instead of the Asp.net..

I hope and I believe, all the works that we are doing in MVC, can be also done by the Asp.Net...

So, the client can use the same old technology and there is no need to hit their head in the wall for switching to new technology..

PS: The advantages like areas, routing are good and makes the work more easier for the developer and the client is not going to do any thing with this. He just want the final output.

May I know, is there any reason, that makes the client to go with the MVC.

Thanks.

vendredi 22 juillet 2016

Losing Cookies and Session Variables during AuthorizeCore

I'm currently working on getting a test environment stood up (it is currently called DEV) and am experiencing some weird issues.

When you first come to the site, we have an agreement page. Hitting the "I Agree" button will force the user through an action to check to see if they are a member of the site already or not. We do use a demo mode also, but that is not part of the issue.

The issue I'm currently experiencing is the following. Initially in the method, we create a cookie called "siteaccept". Once that is created, we determine if the site is in demo mode or not, then move on to getting the user (actual user or demo user). Once the user is found, we log their Id in a cookie called "cntPOC", and also create a Session variable by the same name with the same data (original developers wrote much of this convoluted logic which I want to change before someone asks why keep a Session and Cookie). We then do a RedirectToAction to the main page of the site.

Here is where the issue comes into play. The main page of the site's action has a CustomAuthorizeAttribute decoration on it. In our CustomAuthorizeAttribute class, we have OnAuthorizion and AuthorizeCore being overrode. OnAuthorizion fires off first, however, it uses base.OnAuthorization. Once that is called, AuthorizeCore is called. In AuthorizeCore, we check for the "siteaccept" cookie, followed by a check on the "cntPOC" Session. If both are there, we return true, otherwise false if either fails.

On not only my local environment but the DBA's, this works without a hitch. I see our Cookies and Session variable. However, on our DEV environment, both the Cookies and Session variable are missing. We have IE 11 configured to allow Cookies, yet we cannot get them once we leave the Action and proceed into the CustomAuthorizeAttribute.

I did find I can find the Cookie today if I check HttpContext.Current.Response instead of HttpContext.Current.Request, but that is the incorrect way to do it obviously.

Below is my code. I'm fairly certain since the code works on my local environment, it should be fine in our DEV environment. Also a quick note, our production environment does work, so the code obviously functions. It's a question now of why does the DEV environment not.

Index method in MainController.cs

    [HttpPost]
    public ActionResult Index(FormCollection frmCollection)
    {
        try
        {
            Response.Cookies.Remove("bracmisaccept");

            HttpCookie cookie = new HttpCookie("bracmisaccept");
            cookie.Value = "true";
            Response.Cookies.Add(cookie);

            ...

            //Demo Mode
            var poc = new HttpCookie("cntPOC");
            cookie.Value = "7578";
            Response.Cookies.Add(poc);

            Session["cntPOC"] = 7578;

            return RedirectToAction("ApplicationSelection");
        }
        catch (Exception ex)
        {
            logger.LogError("Main Index", ex);
            return PartialView(@"../Error/ExceptionHandling");
        }
   }

   [CustomAuthorizeAttribute]
   public ActionResult ApplicationSelection()
   {
        return View();
   }

CustomAuthorizeAttribute.cs

        public string RedirectUrl = "~/Main/SessionTimeout";
        public string CookieExpiredRedirectUrl = "~/Main/Index";
        public string AjaxRedirectUrl = "~/Error/AjaxError";
        private bool _isAuthorized;
        private bool _isCookieExpired;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (HttpContext.Current.Request.Cookies["siteaccept"] == null)
            {
                return false;
            }

            if (HttpContext.Current.Session["cntPOC"] == null)
            {
                return false;
            }

            return true;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!_isAuthorized)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.HttpContext.Response.End();
                }
                else
                {
                    if(_isCookieExpired)
                        filterContext.RequestContext.HttpContext.Response.Redirect(CookieExpiredRedirectUrl);
                    else
                        filterContext.RequestContext.HttpContext.Response.Redirect(RedirectUrl);
                }
            }
        }

I'm fairly certain the code is fine, but I did read in a few articles that AuthorizeCore may or may not have the Cookies and Session variables at times. I just wanted to find out if I'm wasting my time with changing the code or if it's the box we have this site on. The server is super locked down, so yeah, kind of annoying...

jeudi 21 juillet 2016

How to use MVC Forum Existing project

I am creating MVC project . using Entity framework . i want add disucssion Forum using MVC forum .how to add MVC forum Existing Project already created Database all.now i want discussion forum MVC Project . how can i add Forum MVC existing Project

mercredi 20 juillet 2016

How to make drop down inside a JQgrid?

As title above how to make a drop down inside a jqgrid with a value of AM and PM?. Please share in jsfiddle. Thanks.

Delete many records with id list - MVC

I want to delete many records with id list send to server MVC.

idlist=[1,2,3,4...]

Ajax :

    $('#btn-delete').click(function () {
        var idlist =new Array();
        $('.ckbox').each(function () {
            if ($(this).is('checked')) {
                idlist.push(parseInt($(this).val()));
            }
        });

        $.ajax({
            type:'POST',
            url:@Url.Action("Delete","Product"),
            dataType:'json',
            contentType:'application/json',
            data:JSON.stringify(idlist)
        });

    });

In Action( i use Entity Framework ) :

[HttpDelete]
public ActionResult (...)
{
....
}

. How can I get idlist and delete records with this idlist ?

IE 8 cannot display the web page form when navigate from asp.netg form to mvc view

IE 8 cannot display the web page form when navigate from asp.netg form to mvc view but it works as expectedc in other browser.

mardi 19 juillet 2016

mvc dropdown date range (every 15 days)

I have this to get the current year

var curdate = new Date();
var ycurdate = curdate.getFullYear();
$("#year").val(ycurdate);

And this one is to get the range of the date into dropdown.

function LoadDTRPeriod() {
    var year = $("#year").val();
    var drpName = "DTRPeriod";
    var url = '../Request/getPeriodByYear/?&year=' + year;
    if (year != "") {
        $.ajax({
            url: url,
            type: 'POST',
            async: false,
            success: function (response) {                  
                var drps = (response.list);
                var selectedDeviceModel = $("#" + drpName + "");
                var pCount = (response.count);
                $("#" + drpName + " > option").remove();
                for (i = 0; i < pCount; i++) {
                    selectedDeviceModel.append($("<option/>").val(drps[i].Value).text(drps[i].Text));
                }
            },
            error: function (response) {
                alert(response.responseText);

            }
        });

    }
}

For example the current year is 2016 but my dropdown return from 2001 not 2016. How can I do it?

Set and Get the default value of checkbox in ASP.NET mvc

I am using Checkbox in my ASP.Net MVC project,

I can set check box by default as unchecked.

Age:
<input class="associationCheckbox" type="checkbox" name="age" />

When I post the form (For has only checkbox), the checkbox is not showing in formCollection (Here expected name and value are age, ‘false’).

Using below code,I was reading the velues.

 [HttpPost]
    public ActionResult Index(FormCollection formCollection)
    {
        foreach (var key in formCollection.Keys)
        {
            var value = formCollection[key.ToString()];
        }


        return RedirectToAction("CorticonIndex", "Test");
    }

If I check the check box at run time, then submit the form. I can get the name and value.

How to get the default values(false)If I don’t check checkbox?

I tried setting value property using model property but same issue is coming.

Model Class:

public bool CheckBoxvalue { get; set; }

this.CheckBoxvalue=false

Age: <input class="associationCheckbox" type="checkbox" name="age" value=@Model.CheckBoxvalue />

Can someone suggest me how to set and get default value.

I had look at below post from stack overflow but didn't info for my requirement.

How to set a CheckBox by default Checked in ASp.Net MVC

http://ift.tt/2a8vuj5

Thanks, Balu

lundi 18 juillet 2016

Calling a partial view in mvc3

This might be a duplicate title but I have a different question. I have this code

if ( Roles.IsUserInRole(User.Identity.Name, "divisionhead") && Roles.IsUserInRole(User.Identity.Name, "director"))
{
    return PartialView("_FieldAssignment");
}           
else
{
    return PartialView("_FieldAssignmentForEmployee");              
}

Now my question it is possible to return two(2) partial view?. If possible how?. Thanks.

required attribute not generating in mvc partial razor view

@model eDurar.Models.BuyOnlineAddress

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>BuyOnlineAddress</legend>

        <div class="editor-label">
            Address Details
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Details, new {@required="required" })
            @Html.ValidationMessageFor(model => model.Details)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

This is partial view, in the html generated, there is no required attribute

When I manually insert it in the html editor, works fine, but this method usually works for normal views

I haven't loaded any scripts this time

dimanche 17 juillet 2016

Can I run OWIN Middleware in an older MVC3 application

We are specifically trying to run SignalR in an older MVC3 application. We went down to v1.2 and it still throws an obsolete exception on the MapConnection method and wants to use AppBuild.MapConnection instead.

Is there a way to run SignalR in Owin in an older MVC3 application? It need not be SignalR really, any Owin middleware will do

Quartz.Net schedule to reload asp mvc action method every 30 seconds

I am trying to reload ActionMethod named Status every 30 seconds, but for some reason return RedirectToAction doesnt work properly

Here is my setup.

Job Class:

public class RedirectJob : IJob
{

    public void Execute(IJobExecutionContext context)
    {

        TestController c = new TestController();

        c.RedirectToStatus();

    }

}

Scheduler:

 public class JobScheduler
   {
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

            IJobDetail job = JobBuilder.Create<RedirectJob>().Build();

            ITrigger trigger = TriggerBuilder.Create()
      .WithIdentity("myTriggerName", "myTriggerGroup")
      .StartNow()
      .WithSimpleSchedule(x => x
      .WithIntervalInSeconds(30)
      .RepeatForever())
      .Build();

            scheduler.ScheduleJob(job, trigger);
        }
   }

Action Methods

public ActionResult Status()
{

  ISchedulerFactory sf = new StdSchedulerFactory();
  IScheduler sched = sf.GetScheduler();

  bool jobStarted = sched.IsStarted;

  if (!jobStarted)
  {
  JobScheduler.Start();
  }


  return View();

}



  public ActionResult RedirectToStatus()
  {

    // Used just to redirect to Status

    return RedirectToAction("Status", "Test");

  }

I have tried this but Is it possible to redirect to action method from a class ?

Any help would be great.

Thank you.

samedi 16 juillet 2016

asp mvc reload page every 30 seconds when browser is minimized

Actually we Play a notification sound when some update happens in database, so I am trying to reload a ActionMethod every 30 seconds when browser in minimized, this works fine in Firefox , but in Chrome this doesn't work.

Scenario:

Minimize the browser and leave the computer idle.

I have tried two methods:

Method 1:

   <meta http-equiv="refresh" content="30;URL=http://example.com/" />

Method 2:

 <script>

   $(document).ready(function () {

   setTimeout(function(){
    window.location.reload(1);
    }, 30000);

    });

 </script>

After reading this post , It seems when Chrome is minimized it sets Javascript setInterval and setTimeout to an idle state, because browser performance improvements affects the executions of Javascript intervals.

So Can i use Scheduled Tasks like FluentScheduler , Quartz.NET or Hangfire to reload a ActionMethod every 30 seconds ?

Any help would be great.

scraping HTML content of dynamically generated web page in asp.net mvc application

i tried this but page is dynamically generated by javascript therefore, required result not achieved. string urlAddress = "http://ift.tt/29Q75jm"; string data = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            data = readStream.ReadToEnd();

            response.Close();
            readStream.Close();
        }

how can it possible?

vendredi 15 juillet 2016

How to make error messages configurable in Umbraco 7?

I am creating a brand new website in Umbraco 7 as backend and ASP.NET MVC as code base. I am want to add the error messages in Umbraco(CMS) as my web site is multilingual. Now the problem is how do make the error messages configurable. I have created a Utilitiy class which will have all the constants define which will store the error messages. Following is that class:

namespace MCA102.BusinessLogic

{ public sealed class Utility { private Utility() { }

    public const string Val1 = /get message from umbraco/
    public const string Val2 = "";

}

}

what should i write after in val1 declaration ? Which umbraco classes I should add at the top ?

unable to get responce Http put upload 1.5 gb files c#

The following code is creating file on remote cloud

  1. up to 800mb files are uploading to cloud
  2. steps here for upload files A). waiting for the file is available B).taking stream from file c). upload process
  3. (bug-1)when user exceeded 1 GB or more file is displaying on cloud but failed to get HTTP status code(Http response)4

4.(bug-2) failed to upload and process is taking too much time

Goal : upload large files as much as possible (min 2 gb file need to upload)

        var fileFolderObj1 = new FileFolder();
        var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
        code = HttpStatusCode.OK;
        HttpWebResponse response = null;

        if (logService != null)
        {
            var sb = new StringBuilder();
            sb.AppendLine("Parameters:");
            sb.AppendLine("CloudId: " + cloudId);
            sb.AppendLine("NewName: " + newName);
            sb.AppendLine("ParentId: " + parentId);
            sb.AppendLine("FileSize: " + fileSize);
            sb.AppendLine("FilePath: " + filePath);
            sb.AppendLine("URL: " + postURL);

        }

        try
        {
            string selectedFile = null;
            selectedFile = filePath;
            var fi = System.IO.Path.GetFileName(filePath);

            ////commented for some reason
            var postParameters = new Dictionary<string, object>();
            postParameters.Add("file", new FileParameter(filePath,  ""));
            postParameters.Add("parentId", parentId);
            postParameters.Add("newName", fi);
            postParameters.Add("cloudId", cloudId);
            postParameters.Add("isSecure", isSecure);
            postParameters.Add("fileSize", fi.Length);
            var userAgent = "Desktop";
            var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            var uri = new Uri(postURL);
            var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
            this.SetBasicAuthHeader(createFileRequest, userId, password);
            createFileRequest.ContentType = "multipart/form-data";
            createFileRequest.Method = "PUT";
            //--- mahesh updated --//
            createFileRequest.ProtocolVersion = HttpVersion.Version11;
            createFileRequest.ReadWriteTimeout = 1000000000;
            //------- mahesh end --//
            createFileRequest.Timeout =  System.Threading.Timeout.Infinite;
            createFileRequest.KeepAlive = false;/*true;*/
            createFileRequest.UserAgent = userAgent;
            createFileRequest.CookieContainer = new CookieContainer();
            try

            {
                using (var requestStream = createFileRequest.GetRequestStream())
                {

                    WriteMultipartFormData(postParameters, formDataBoundary, requestStream);

                    requestStream.Close();
                    logService.Debug("CloudFuzeRemoteService", "CreateFile", " REQUEST STREAM IS CLOSED File Path: {0} ", filePath);
                }
                using (response = (HttpWebResponse)createFileRequest.GetResponse())
                {

                    var reslut = new StreamReader(response.GetResponseStream()).ReadToEnd();

                    fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);


                }
            }
            catch (Exception exc)
            {
                fileFolderObj1 = null;
                if (logService != null)
                {

                if (response != null)
                {
                    code = response.StatusCode;
                }
            }

        }
        catch (Exception exc)
        {

        }
        logService.Debug("CloudFuzeRemoteService", "CreateFile", " Befor Return object  IS Called File is upload File Path: {0} ", filePath);
        return fileFolderObj1;
    }

    private static readonly Encoding encoding = Encoding.UTF8;

    private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream)
    { 
        var needsCLRF = false;
        foreach (var param in postParameters)
        {
            // Skip it on the first parameter, add it to subsequent parameters.
            if (needsCLRF)
            {
                requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
            }
            needsCLRF = true;
            if (param.Value is FileParameter)
            {
                var fileToUpload = (FileParameter)param.Value;
                // Add just the first part of this param, since we will write the file data directly to the Stream
                var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                    boundary,
                    param.Key,
                    fileToUpload.FileName ?? param.Key,
                    fileToUpload.ContentType ?? "application/octet-stream");

                requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
                // Write the file data directly to the Stream, rather than serializing it to a string.
                FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
                int bufferlenth = 100;
                byte[] buffer = new byte[1024*70];

                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, bufferlenth /*buffer.Length*/)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();

            }
            else
            {
                var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                    boundary,
                    param.Key,
                    param.Value);
                requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
            }
        }

        // Add the end of the request.  Start with a newline
        var footer = "\r\n--" + boundary + "--\r\n";
        requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
    }

jeudi 14 juillet 2016

Read excel file into database using mvc3 and stored procedure and without using any driver(Ace/Jet) and without EPPlus dlls

I have a requirement to upload and read an excel file into the database using a stored procedure but i can not use any external dlls like EPPlus or drivers like Jet/Ace. Can anyone help me to do this? I searched on so many sites but none met my requirements. This should be implemented in MVC 3. I have created the view. And the Browse option is working fine. All i need to know is how to upload and read.

mercredi 13 juillet 2016

How do I avoid unnecessary dll recompilation after adding MVC3 views?

I have an Asp.net MVC3 customer portal application with a view folder hierarchy which allows me to brand each customer by putting new razor views into a Views/Custom folder. For example, this would allow me to create a custom wrapper and landing page for customer "Acme":

Views/Custom/Acme/Shared/_Layout.cshtml
Views/Custom/Acme/Home/Index.cshtml

The issue I'm having is that creating customized views is far more common than modifications to the application's controllers. However, when I add a new view under the Custom directory and publish my changes, the application's dlls are getting rebuilt.

I'm having problems with shadow copies on my production server and have to take the entire site down when I deploy new dlls (a separate issue, but one I'm resigned to avoid for now).

Is there a way to tell Visual Studio 2010 that adding folders and razor templates do not require the dlls to be recompiled? The Custom folder has Namespace Provider set to True and the Razor templates in each subdirectory are marked as Content, Do Not Copy.

Actual Folder Structure

Use Boostrap for already created Application of MVC 3

I already create my application using MVC 3. Use my customize CSS and JS file. Now I want to use Bootstrap for my application. Is it good to use Bootstrap now? Have any solution for customize CSS and JS using Bootstrap?

how to Render a PartialView inside a main view

heloo guys m working on a application my requirment is to add a createView (to Enter Data) inside the indexView (Where m Showing all the data in a table from databae) to enter data from the same view, here is my code see if you can help.. Controler Code

   // GET: /Brands/
    public async Task<ActionResult> Index()
    {
        return View(await db.Brands.ToListAsync());
    }
  // GET: /Brands/Create
    public ActionResult Create()
    {
        return PartialView("_Create", new BootstrapModalTest.Models.Brand());
    }

    // POST: /Brands/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 async Task<ActionResult> Create([Bind(Include="BrandId,BrandName,BrandCode")] Brand brand)
    {
        if (ModelState.IsValid)
        {
            db.Brands.Add(brand);
            await db.SaveChangesAsync();
            return PartialView("_Create", brand);
        }

        return PartialView("_Create", brand);
    }

and Here is Index.cshtml View Code..

div class="panel panel-primary">
<div class="panel-heading" style=" padding:2px 7px 0px 6px;"><h4>Frames</h4></div>

<div class="panel-body " style="padding:4px;">
    @{Html.RenderAction("Create", "Brands");}

</div>

<table class="table table-bordered>
//some data

mardi 12 juillet 2016

How to install two nuget packages with diffrent newtonsoft.json dll versions in single Asp.Net MVC project?

Error: Install-Package : Unable to find a version of 'Newtonsoft.Json' that is compatible with 'Microsoft.AspNet.WebApi.Client 5.2.3 constraint: Newtonsoft.Json (>= 6.0.4)', 'Microsoft.Owin.Security.OAuth 3.0.1 constraint: Newtonsoft.Json (>= 6.0.4)', SamplePackage1.Logging 3.0.0.1 constraint: Newtonsoft.Json (>= 7.0.1 && < 8.0.0)', 'SamplePackage2.Serialization 2.0.0.1 constraint: Newtonsoft.Json (>= 7.0.1 && < 8.0.0)'. enter image description here

Description I got above error while installing two packages from nuget in my project.

According to me, this is happening due to inconsistency in Newtonsoft.json package's version used in Package1 & Package 2.

To use both packages at a time in same project, What should I do ?

Thanks Ketan

Issue while calling Controller Method

I have two controller called FormController and CorticonResponseController.

FormController:

public ActionResult Index(FormCollection formCollection) {

        Session["CorticonServiceEndpoint"] = this.CorticonServiceEndpoint;
        Session["CorticonServiceName"] = this.CorticonServiceName;
        Session["CorticonServiceMajorVersion"] = this.CorticonServiceMajorVersion;
        Session["CorticonServiceMinorVersion"] = this.CorticonServiceMinorVersion;

        Session["payLoad"] = “Test”;

        return RedirectToAction("CorticonIndex ", “CorticonResponseController”);
    }

CorticonResponseController:

    public ActionResult CorticonIndex()
    {
        string payLoad = (string)Session["payLoad"];

        string CorticonServiceEndpoint = (string)Session["CorticonServiceEndpoint"];
        string CorticonServiceName = (string)Session["CorticonServiceName"];
        string CorticonServiceMajorVersion = (string)Session["CorticonServiceMajorVersion"];
        string CorticonServiceMinorVersion = (string)Session["CorticonServiceMinorVersion"];

        var viewModel = this.Model.GetViewModel(payLoad);


        return View ("Default", viewModel);
    }

Here, I was sending some information from FormController to CorticonResponseController. In CorticonResponseController, I made some calculations and returning the view with the model. Hence the URL is changing from http://localhost:35583/banking/open-an-account To http://localhost:35583/banking/open-an-account/CorticonIdex.

However, I don’t want to change the URL so I have modified my code as below.

CorticonResponseController:

   public void CorticonIndex()
    {
        string payLoad = (string)Session["payLoad"];

        string CorticonServiceEndpoint = (string)Session["CorticonServiceEndpoint"];
        string CorticonServiceName = (string)Session["CorticonServiceName"];
        string CorticonServiceMajorVersion = (string)Session["CorticonServiceMajorVersion"];
        string CorticonServiceMinorVersion = (string)Session["CorticonServiceMinorVersion"];

        var viewModel = this.Model.GetViewModel(payLoad);
        TempData["ResponseController"] = viewModel;
    }

FormController:

    public ActionResult Index(FormCollection formCollection)
    {

        Session["CorticonServiceEndpoint"] = this.CorticonServiceEndpoint;
        Session["CorticonServiceName"] = this.CorticonServiceName;
        Session["CorticonServiceMajorVersion"] = this.CorticonServiceMajorVersion;
        Session["CorticonServiceMinorVersion"] = this.CorticonServiceMinorVersion;

        Session["payLoad"] = “Test”;

        CorticonResponseController obj = new CorticonResponseController();
        obj.CorticonIndex();


        CorticonResponseModel viewModel = (CorticonResponseModel)TempData["ResponseController"];

        string controllerName = DecisionServiceProgram.GetResponseWidgetName();

        return View("Default", viewModel);
    }

Here,In my FormController, I was calling CorticonResponseController method and getting CorticonResponseModel data using TempData and then returning the view.

I am facing the issues while executing the controller.

Can someone help me how to resolve the issue?

lundi 11 juillet 2016

how to change connection string db value app setting to web config

currently MVC project.previous developer database connected app settings now i change to Web config

i have changed code Like this appsettings to webconfig

<appSettings>
<add key="TickPortalSql" value="Server=1.34.34.4.;Database=montage;User ID=Montage;Password=pwd;Trusted_Connection=False;" />
</appSettings>

this code change to web config

<connectionStrings>

      <add key="TickPortalSql" value="Server=1.34.34.4.;Database=montage;User ID=Montage;Password=pwd;Trusted_Connection=False;" />
  </connectionStrings>

Previous developer using AppSettingsReader

public abstract class HomeSqlDBRepository
    {
        public string ConnectionString { get; set; } = AppSettingsReader.ReadString("thenna");
        const int MaxItemCount = 1000;
        public enum SqlExecuteType
        {
            Scalar, NonQuery, Reader
        }
        public async Task<string> ExecuteSqlAsync(string procname, SqlExecuteType executiontype, IDictionary<string, string> parameters)
        {
            string ret = "";

            using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
            {
                using (SqlCommand sqlCmd = new SqlCommand(procname, sqlConn))
                {
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    foreach (KeyValuePair<string, string> kvp in parameters)
                    {
                        sqlCmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
                    }
                    sqlConn.Open();
                    if (executiontype == SqlExecuteType.Scalar)
                        ret = (await sqlCmd.ExecuteScalarAsync()).ToString();
                    else if (executiontype == SqlExecuteType.NonQuery)
                        ret = (await sqlCmd.ExecuteNonQueryAsync()).ToString();
                    sqlConn.Close();
                }
            }

            return ret;
        }

but i getting error ex exception here code

using Microsoft.Azure;

  public static class AppSettingsReader
    {
        public static string ReadString(string key)
        {
            try
            {
                return CloudConfigurationManager.GetSetting(key).ToString();
            }
            catch(System.Exception ex)
            {
                throw ex;//error 
            }
        }

    public static int ReadInt(string key)
    {
        try
        {
            return int.Parse(CloudConfigurationManager.GetSetting(key).ToString());
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }

    public static decimal ReadDecimal(string key)
    {
        try
        {
            return decimal.Parse(CloudConfigurationManager.GetSetting(key).ToString());
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }

    public static bool ReadBool(string key)
    {
        try
        {
            return bool.Parse(CloudConfigurationManager.GetSetting(key).ToString());
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }
}

any one tell how to change azure app settings read db to web config db read? i have tired many method getting Error ..

samedi 9 juillet 2016

how to Add Create View in Index View in mvc

heloo guys can anyone tells how to add create view in the index view i mean i want to add data from the same view where i am showing the whole data. check my Controler code

public class BrandsController : Controller
{
    private erpOpticalsDBContext db = new erpOpticalsDBContext();

    // GET: /Brands/
    public async Task<ActionResult> Index()
    {
        return View(await db.Brands.ToListAsync());
    }
        // GET: /Brands/Create
    public ActionResult Create()
    {
        return PartialView("_Create", new BootstrapModalTest.Models.Brand());
    }

    // POST: /Brands/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 async Task<ActionResult> Create([Bind(Include="BrandId,BrandName,BrandCode")] Brand brand)
    {
        if (ModelState.IsValid)
        {
            db.Brands.Add(brand);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return PartialView("_Create", brand);
    }

and here is IndexView Code

Frames

<div class="panel-body " style="padding:4px;">
    @{Html.RenderAction("Create", "Brands");}

</div>

<table class="table table-bordered table-hover table-striped table-responsive table-condensed">
    //somedata

How to hide action and controller from url : asp.net mvc

Introduction

I am working on demo application where users can register.Users table have "username" field.There is "detail" action in "home" controller accepting parameter of string "username".

Code

public ActionResult Detail (string username)
{
 return View();
}

Then url will be

http://ift.tt/29oUTDi

Problem

Can i setup route like that ?

http://ift.tt/29nNCYk

If its possible, then please let me know. Any kind of help or reference will be appreciated.

Thanks for your time.

vendredi 8 juillet 2016

how to specify Default value for dropdown i have populated from database using Viewbag in mvc

heloo guys i have populated dropdownlist from database in mvc using Viewbag object now i want to specify default value for it like Select Supplier here is my Controler code..

 public ActionResult Create()
    {
        //IEnumerable<SelectListItem> SuppliersList = db.Suppliers.Select(c => new SelectListItem
        //{
        //    Value = c.Name,
        //    Text = c.Name

        //});            

        ViewBag.SupplierList = new SelectList(db.Suppliers, "Name", "Name");
        return PartialView("_Create");
    }

    // POST: /Frames/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 async Task<ActionResult> Create([Bind(Include="FrameId,Name,FrameCode,FrameFor,Brand,Material,Color,FrameType,FrameShape,Bridge,LensWidth,FrameWidth,TempleLength,LensHeight,FrameWeight,Quantity,PurchaseRate,SaleRate,Supplier,Discription,Status,CreatedOn")] Frame frame)
    {

        if (ModelState.IsValid)
        {
            db.Frames.Add(frame);
            await db.SaveChangesAsync();
            return Json(new { success = true });
        }



        return PartialView("_Create", frame);
    }

and my ViewCode

<div class="col-md-3">
                    @Html.LabelFor(model => model.Supplier)
                    @Html.DropDownList("Supplier", ViewBag.SupplierList as SelectList, new { @class = "form-control"})
                    @Html.ValidationMessageFor(model => model.Supplier)
                </div>

i have two users Passengers and Drivers how can i make one login page for both users in asp.net C#

i have two users Passengers and Drivers how can i make one login page for both users in asp.net C# login page for passengers protected void Button1_Click(object sender, EventArgs e) {

        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand();


        cmd.CommandText = "SP_SELECT_Login1";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;

        cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@Password", txtPassword.Text);

        SqlDataAdapter ad = new SqlDataAdapter();
        DataSet ds = new DataSet();
        ad.SelectCommand = cmd;
        ad.Fill(ds);

        if (ds.Tables[0].Rows.Count > 0)
        {
            Session["UserId"] = ds.Tables[0].Rows[0]["Reg_id"].ToString();
            Session["Username"] = ds.Tables[0].Rows[0]["Fname"].ToString();



            Response.Redirect("Profile.aspx");
        }
        else
        {
            lblMsg.Text = "Incorrect User and Password or Unverify user";
}}

Sql Server fragmentation Problems

enter image description here We have a SQL Server 2012 database with our live project asset tracking system. We are facing some problems in our database including huge number of tables and more than 5 millon rows of data. Basically a problem with same some of the queries on tables (like TrackerMaster, Usercar, TrackerResponse) are taking less time to execute whereas other queries on these tables are tremendously slow to execute.

I am not sure whether it is a fragmentation problem for indexing or not. More precisely, even if we union on two or more queries where query getting very slow to produce result on the database I don't know why it's happening

Can someone please help me resolve this issue or problem? Our MSSql Server Database Images Attachment are given below--Our Asset Tracking Database images

jeudi 7 juillet 2016

redirect and download pdf on click of radio button

Need a suggestion from people more intelligent than me. I have a modal which has 2 things, essentially, 3 radio buttons (Email, PDF, None)and a Yes and NO submit button. On press of radio button I flag hidden variables appropriately to know if the user pressed email or pdf in my controller. Than user presses Yes for saving (happy path), and it will call a controller. This controller will save the changes and redirect to a different page. Now I wanna add to this controller and make it download a pdf. I am doing this by calling my DownloadPDF action.

public ActionResult Main(string id)
//code for doing all the save and other stuff
{
if (viewModel.Email)
{
    SendTestingEmail(viewModel.ConsumerEncryptedID);
}
else if(viewModel.PDF)
{
    DownloadWelcomePDF()
}
return RedirectToAction("ConsumerIndex", "Consumer")

}

    public ActionResult DownloadWelcomePDF(string id)
{
    var htmlWelcomeEmail = db.getHtmlBody(id.DecryptID());
    var converter = new ConvertToPDF();
    var file = converter.ConvertHTMLStringToPDF(htmlWelcomeEmail.EmailBody);
    var fileStreamResult = new FileStreamResult(file, "application/pdf") { FileDownloadName = string.Format("Welcome{0}{1}_{2}.pdf", htmlWelcomeEmail.ConsumerFirstName, htmlWelcomeEmail.ConsumerLastName, DateTime.Now.ToString("yyyyMMdd")) };
    return fileStreamResult;
}

Now since this will also return pdf content I cannot do both these 2 things (redirecting to a different page and downloading ) at the same time. Is there any suggestion, I have been searching internet for a long time. It is essentially download and redirect but download needs to happen only on certain condition (press of radio) and the page should always redirect nonetheless.

Has behaviour of Display Templates changed in MVC5 from MVC3?

I have upgraded from MVC3/Razor to MVC5/Razor.

I have found my Display Template is not reading in the Model value any longer.

The Template is called "MyTemplate":

@model System.Object
@{
if (Model !=null)
{
    //string.Format("{0:0.00}", Model);
    Model.ToString();
}
else
{
    @:-    
}

}

Which is being called by:

@Html.DisplayFor(modelItem => item.myvalue, "MyTemplate")

Model is returning null, when I follow it via the debugger.

Any help with this would be greatly appreciated.

mercredi 6 juillet 2016

How to configure web config of MVC3 to connect in Oracle 11g?

I am having trouble to configure my web config to connect in Oracle 11g and I am using MVC3 as mention in my Title. Like to this link I have the same problem. I have also EDMX to my project how to configure it?. Please help. Thanks

ASP.Net MVC Model Binding Null reference exception , an object refrence is not set to instance of object . " InRequestScope is also not working "

My Query is exactly Similar to this Link below please check and come back

Object reference not set to an instance of an object when using custom model binding

But That query got resolved by using .InRequsetScope Methodin NinjectDependencyResolver.cs

kernel.Bind<EFDbContext >().To<EFDbContext >().InRequestScope();

But i am still getting Null reference Exception while using Custom Model Binding and if i use a normal method in controller to fetch these request from view rather than Model Binder then it works properly , I am Following Pro ASP.net MVC5 Book

Download a file with mvc

I need to allow the user on my site to download a file (xml File)

I tried

 public FileResult DownloadFile(string fileid)
 {
     if (!string.IsNullOrEmpty(fileid))
     {            
         byte[] fileBytes = Encoding.ASCII.GetBytes(FileData);
         return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet,FileName + ".bccx");
     }
         return null;
 }

ajax:

function downloadFile(id) {
        $.ajax({
            url: sitePath + "Controller/DownloadFile?fileid=" + id,
            type: 'post',
            asysnc: false
        })
        .done(function () {

        });
}

but nothing is downloaded

Do Roles and Profiles in ASP.NET MVC3 need changing when porting to MVC5?

I've created a project using ASP.NET MVC3 and now want to port it to MVC5. It uses Membership, Roles and Profiles to authenticate users, as is common in MVC3. However, I understand that MVC5 uses the Identity system instead of Membership. Therefore, I would need to update my Membership logic when porting to MVC5. That brings me to my question: Does the same apply to Roles and Profiles? Will I need to make any changes to them in order to make them compatible with MVC5? If so, any links to further information would be appreciated (unless everything I need to know can be condensed into a brief StackOverflow answer :P).

Value passed through as 'Nothing' When it should be populated

So I'm having an issue passing a param through to my controller.

When I do my Ajax.BeginForm and pass in as follows:

<% Using Ajax.BeginForm("MultiProcess", "Orders", New MultiProcessRequestViewModel With {.SearchParams = Model.SearchParams},New AjaxOptions With {.UpdateTargetId = "ordersOutput", .OnSuccess = "afterRead", .LoadingElementId = "readingOrders"})%>

The value appears as 'Nothing'.

However on the same page if I simply do the following:

<%=New JavaScriptSerializer().Serialize(Model.SearchParams) %>

To try and gauge if the value is set. I can see that the value is indeed set and correct.

The entire section for reference:

<% Using Ajax.BeginForm("MultiProcess", "Orders", New MultiProcessRequestViewModel With {.SearchParams = Model.SearchParams}, New AjaxOptions With {.UpdateTargetId = "ordersOutput", .OnSuccess = "afterRead", .LoadingElementId = "readingOrders"})%>
    <%=New JavaScriptSerializer().Serialize(Model.SearchParams) %>

        <div>
            <%=Html.Hidden("SearchParams", Model.SearchParams) %>
            <%=Html.Hidden("Test", "Just in case") %>
            <%=Html.DropDownList("Process", Model.Processes)%>
            <input type="submit" value="Process selected items" class="FormButton" id="btnMultiProcess" />
            <br />
        </div>  

<%  End Using %>

The test and process params both work. Here is the model for reference:

Public Class MultiProcessRequestViewModel
    Public Property SearchParams As New Orders.OrderSearchFilters
    Public Property Process As String
    Public Property SelectedItems As New List(Of String)
    Public Property Test As String

End Class

Change Password using Update Query

I have Creating MVC5 Project.i Need to Implement Change password Change on my Site.In this only four people have access permission. this field called TP_USERS

 Id PK, int, not null
 UserName   nvarchar(50), null  
 UserEmail  nvarchar(50), null ----------user mail
 DisplayName    nvarchar(50), null
 Password   nvarchar(50), null  ----------Password 
 RoleId FK, int, not null
 IsActive   bit, not null
 ClientId   int, null

above mention useremail and password for login fields. now i want implement change password how to implement change password on my Site . using stored procedure

how to change password and how to update new password database for TP_users table who login currentely

mardi 5 juillet 2016

How can we create charts in excel using closedxml

How to create charts in excel,While exporting data from database to excel sheet..!

I'm exporting data to excel from database.I need to create chart in the excel sheet based on data from database. Below code creates simple excel sheet I need to make changes in the same code to create charts. Please Guide

public ActionResult ExportToExcel()
{
        var workbook = new ClosedXML.Excel.XLWorkbook();
        var worksheet = workbook.Worksheets.Add("SheetOne");
        DocumentFormat.OpenXml.Drawing.PictureLocks piclocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
        worksheet.Cell("A1").Value = "Test data!";
        Response.ClearContent();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=\"PPs_Workflow.xlsx\"");
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        workbook.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        memoryStream.Close();
        Response.End();
        return File(memoryStream, "application/ms-excel", "PPs_Workflow.xlsx");

} 

lundi 4 juillet 2016

ASP.Net Web API 404 error on production server

We are facing an issue after deploying our asp.net web api to production server. 404 not found is occurring after every hit on the api. Following is already installed on production server.

  1. .Net framework 4.6
  2. ASP.Net MVC3

I have also tried multiple solutions found on different forums like register asp.net on iis and adding an entry in System.Webserver but nothing worked for us. Could someone help us to found the root cause of the issue?

When upgrading from MVC3 to MVC5, do I need to upgrade referenced MVC3 projects?

I have created a project using MVC3 and .NET 4. I now want to upgrade it to MVC5. However, my project contains references to other projects that were also made using MVC3 and .NET 4. Will I need to upgrade those projects to MVC5 in the same way in order for everything to still be compatible?

How to give javascript unique ID in htmleditfor method in .net MVC?

I want to give a unique id to htmleditfor method. I want to add Jquery datepicker in it. Please guide...

@Html.EditorFor(model => model.AdExpiryDate, new { htmlAttributes = new { @class = "form-control", placeholder = "MM/DD/YYYY" } })

dimanche 3 juillet 2016

Can anyone please say how to make an auto complete in jquery with MVC Model Select list

Can anyone please say how to make an auto complete textbox in jquery with MVC Model's Select list as below

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CentralAudit.Models
{
[Serializable]
public class InwardModels
{
public SelectList AllSpokes { get; set; }
}
}

MVC - Cookie not getting set in IE only (Works in FF and Chrome)

I have run into a weird problem when I am trying to log in to one of the our websites in test environment. Logging in using FF or Chrome sets all the cookies (email, id and type) but in IE Edge only email and type session is getting set and id goes missing. Because of this, I can't login to the website in IE but it works flawlessly in Firefox or Chrome. See the attached snapshots.

Chrome enter image description here

Firefox enter image description here

IE Edge (i get same behaviour in other IE versions as well). enter image description here Any pointers will be much appreciated.

samedi 2 juillet 2016

How i get the user and atach to an object javacript

 $http.get("api/location/getReviews/" + $routeParams.id)
                .success(function (data) {
                    $scope.reviews = {};
                    $scope.reviews = data;
                    angular.forEach($scope.reviews,
               function (value, index) {
                   $http.get("api/user/" + value.UserId)
                       .success(function (user) {
                           $scope.value.User = user;
                       });
               });
                });

I have the following code , and what i am trying to do is to get user from userId and atach to a review , to send it into view because my review has a userId , and i need user email,and when i list the reviews i want to show the email not the id but i don't know how ...it gives me cannot read property or undefined User . Can someone help me please?