mercredi 30 novembre 2016

In EF stream is null when seed method run with data from CSV file

I have a large dataset formated CSV file type, I want to add all the data into my EF database from CSV file. But when run seed method, it creates error Error Message is

Value cannot be null. Parameter name: stream

protected override void Seed(Drug_Information_System.Context.DrugInformationContext context)
    {

        Assembly assembly = Assembly.GetExecutingAssembly();

        string resourceName = "Drug_Information_System.Domain.SeedData.PharmaCompanies.CSV";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                CsvReader csvReader = new CsvReader(reader);
                csvReader.Configuration.WillThrowOnMissingField = false;

                var records = csvReader.GetRecords<PharmaCompany>().ToArray();

                foreach (PharmaCompany values in records)
                {
                    context.PharmaCompanies.AddOrUpdate(values);
                }
            }
        }
        context.SaveChanges();
    }

I am not sure whats wrong in my code...

Add objects and save image C# fabric.js

js]1. using asp.net mvc3. i want to draw text and rectangle on the image as group. text and rectangle can be added multiple times. after adding groups i want to save that image, Accuracy is important
I had two choices . First choice is to use canvas.toJSON(). this approach i have to create object using C# graphics class which is painfull and not accurate. second is to export canvas as base64 which is accurate. .
Here is what i have done so far jsfiddle
here is the code giving exception

function SaveResultImage() {
  canvas.deactivateAll().renderAll();
  var base64String = canvas.toDataURL("image/jpg");
  if (!fabric.Canvas.supports('toDataURL')) {
    alert('This browser doesn\'t provide means to serialize canvas to an image');
  } else {
    console.log(base64String);
    // save image posting base64String using ajax// this is working fine
  }
}

exception: VM1226 fabric.min.js:4 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.(…)

lundi 28 novembre 2016

Value cannot be null. Parameter name: incomingMarkupParser

I have an MVC3 project that I need to work on and every time I try to run it I get this Compilation exception;

Value cannot be null. Parameter name: incomingMarkupParser

How do I fix this? It looks like a problem with Razor. My web.config in the Views folder is;

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler" />
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler" />
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>


  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="ITOC4.HtmlHelpers" />
        <add namespace="ITOC4.Models" />
        <add namespace="ITOC4.Web.Models" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="Omu.Awesome.Core"/>
        <add namespace="Omu.Awesome.Mvc.Helpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>
</configuration>

and in the main folder (with lines removed for brevity) the web.config is;

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="elmah">
  </configSections>
  <elmah>
  </elmah>
  <appSettings>
  </appSettings>
  <connectionStrings>
  </connectionStrings>
  <system.web>
    <customErrors mode="Off" defaultRedirect="~/Error/Unknown">
      <error statusCode="404" redirect="~/Error/NotFound" />
    </customErrors>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <sessionState timeout="2880"></sessionState>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership>
    </membership>
    <profile>
    </profile>
    <roleManager enabled="true">
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.WebPages" />
        <add namespace="Omu.Awesome.Core" />
        <add namespace="Omu.Awesome.Mvc.Helpers" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.10.0" newVersion="2.6.10.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="PagedList" publicKeyToken="abbb863e9397c5e1" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.17.0.0" newVersion="1.17.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
  </entityFramework>
</configuration>

And in the packages config I have these lines;

  <package id="Microsoft.AspNet.Mvc" version="3.0.50813.1" targetFramework="net40" />
  <package id="Microsoft.AspNet.Razor" version="1.0.20105.408" targetFramework="net40" />
  <package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" targetFramework="net40" />

mercredi 23 novembre 2016

mardi 22 novembre 2016

Error Format DateTime MVC

enter image description here

I set Format DateTime but have problem this error: LINQ to Entities does not recognize the method "System.String" ToString(System.String)

jeudi 17 novembre 2016

QR Code Scanner from android to web program

I've seen this LINK for reading a QR Code that generated. I am thinking that It is possible to use something like this but the scanner is from android phone and the output is in the web system. Just like the barcode reader it read the barcode and the output is in a Computers. Can this link be modify or can anyone point me to the right link on how to achieve my goal?. Please Thanks. I am searching this for a months

mercredi 16 novembre 2016

Not able to render label tag on a view dynamically

I have below piece of code in .cshtml file.

<div class="row">

            <input type="text" placeholder="Enter POR ID" id="porID" class="col-md-2 input-sm" name="porTextBox">
            <button class="btn btn-primary col-md-2 btn-sm" style="margin-left:15px;width:150px;" type="submit" id="btnCreateTFSItems"><strong>Create TFS Items</strong></button>
            @if (TempData["formState"] != null)
            {
                //@Html.Label("lblsuccess", "Successfully created TFS Work Items!")
                <label id="lblsuccess" style="color:green; visibility:visible">   Successfully created TFS Work Items!</label>
            }
        </div>

and the button is calling the below function in script tag :

<script type="text/javascript">
$(document).ready(function (e) {

    $('#btnCreateTFSItems').click(function () {
        var txt = $('#porID');
        var errorLabel = $('#lblError');
        if (txt.val() != null && txt.val() != '') {
            //alert('clicked');

            $.ajax({
                url: '@Url.Action("CreateWorkItems", "Tables")',
                type: 'POST',
                data: { 'porTextBox': $('#porID').val() }
            });
           // alert('Successfully added');
        }
        else {
            errorLabel.text("Please enter valid PORID");
            return false;
        }
    });

    $("#porID").keypress(function (e) {
        var errorLabel = $('#lblError');
        errorLabel.text("");
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
});

The problem is in .cshtml file, it is checking the condition but its not adding the label. The reason may be because page is not refreshing to render the label. I am new to UI development so I have tried certain options which i found on net but wasn't able to make it work. Is there any way i can achieve this ?

mardi 15 novembre 2016

MVC JQuery Grid Server side pagination

I'm working on a MVC 3 project that uses jq Grid. I want to use server side pagination. The ultimate goals are to return a row count, let the user filter by a few fields, populate the grid with the first page of records (20 records), have the next icon at the bottom of the grid run a Linq to SQL query that populates the next page, and I want to use the built in search functionality to filter the grid and so I need to override that functionality with custom code. I've written a stored procedure that will return the data for the specified page. I need help with the rest.

Rate product on the basis of comment

I faced difficulty in rate the product. My website has different products and every product has comment box. So how can i rate the product on the basis of comments instead of manually rate the product. Is there any source from where i learn this. My basic problem is rate the product on the basis of comments that is given by user.

lundi 14 novembre 2016

How to send mail automatically asp.net mvc

How to send mail automatically before 2 day and after deactivate of user account

Poblem adding reference to System.Web.Mvc 3.0.0.1

I got an old a .net application that is not mine. It was using the MVC 3.0.0.0 but I upgraded to the MVC 3.0.0.1. I am trying to make it run but I can not add the reference to System.Web.Mvc. I added the reference but next time I open it is unchecked.

I have to add that I am new with asp.net and MVC so maybe I am missing something obvious.

How should I add all the reference that I am missing ?

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.1" />
  </dependentAssembly>
</assemblyBinding>

Attach Model to Existing View

I am new to MVC. Developing MVC case study, I have created the view without attaching the model and done few design on that.

Now we would like to attach model to the existing view, how to attach the model to that.

I have tried to open the model attaching dialog box. I could not open the model attaching dialog box, if i creating new view its displaying the dialog box to attach the model. i can not do the same thing for the already created view

how to attach the model for existing View?

dimanche 13 novembre 2016

How to recover data through a foreign key

I have 2 tables Users and Services, linked by an associative table called contract wich conatain id_User and id_Service as foreign keys. I want to recover those two foreign keys by clicking on a button wich create a new contract, not only the FK but also some values such as service name for id_Service, cuz table Contract take this attribut as his name too, and how to pass his value in the controller!!? plz any solutions??

jeudi 10 novembre 2016

C# - "An element with the same key was already added"

I work in ASP.NET MVC and I am blocked(surrounded) in my model with this damned error " an element with the same key was already added", I understand not at all why while I have almost the same code with different requests in other methods of my model.

And I do not think that the problem can come from the request because I have already used her(it) as before in another project..

Here is the code of my model:

public Dictionary<string,string> getDonnee()
{
    Dictionary<string, string> list = new Dictionary<string, string>();

    SqlConnection cn;
    SqlDataAdapter da;
    DataSet ds;

    cn = new SqlConnection(CS_DW);
    cn.Open();

    da = new SqlDataAdapter("select distinct(ltrim(rtrim(cpic))) as code, cpic as lib from [DW].[dbo].[PIC_PROD_S001] ", cn);
    ds = new DataSet();
    da.Fill(ds, "code");

    list.Add("REEL", "REEL");
    foreach (DataRow row in ds.Tables["code"].Rows)
    {
        list.Add(row["code"].ToString(), row["lib"].ToString());
    }

    cn.Close();
    return list;
 }

My controller :

public ActionResult rspic002()
{
   ViewData["Ddl_donnee"]  = model.getDonnee();

   return View();
}

My view :

List<SelectListItem> listDonnee = new List<SelectListItem>();

foreach (KeyValuePair<string, string> key in ViewData["Ddl_donnee"] as Dictionary<string, string>)
{
        SelectListItem donnee = new SelectListItem();
        donnee.Value = key.Key;
        donnee.Text = key.Value;
        listDonnee.Add(donnee);
}

Thank you in advance for your help

mardi 8 novembre 2016

How to exclude asp.net identity default table and How to use Asp.net Identity in asp.net API

I have tried to remove deafault table of asp.net identity.I need to create user in asp.net table customized table.How can do ?

DatePicker in asp.net mvc visual basic

Helo, I'm working on a small Project with Visual Studio 2015, ASP.NET 5, MVC. I need to know how to develop in visual basic to use a datepicker to enter dates using a calendar in the date fields.

lundi 7 novembre 2016

Getting error "the element 'httpCookies' has been locked in a higher level configuration"

I'm getting the error "The element 'httpCookies' has been locked in a higher level configuration" when i try to access an asp.net mvc 3 application. This happens when i add the line below inside my <system.web> section.

<httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" />

This is happening on windows server 2003 (IIS 6). The error doesn't occur on windows 7 & Windows 2008 R2 (IIS 7 & above)

I have checked the machine.config file on both the windows 2003 server and my windows 7 development machine and it contains below line on both machines.

<section name="httpCookies" type="System.Web.Configuration.HttpCookiesSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

dimanche 6 novembre 2016

Creating an IF - Else Statement in MVC Razor [duplicate]

This question already has an answer here:

I am getting an error Object reference not set to an instance of an object. in running my MVC Html Razor. I search on google on how to create an IF-Else in razor and found some good answer. But in my case I am getting an error.

My Code

<td  style="text-align: left" >
                    <div id="divEBSN">
                    @if (Model.RCEducationalBackground.School.SchooldName != null)
                    {
                       <span style="color: Red">@Html.DisplayFor(model => model.RCEducationalBackground.School.SchooldName)</span>    
                    }
                    else { 
                        <span style ="color:Red">@Html.DisplayFor(model => model.RCEducationalBackground.SchoolNameEducBG)</span>
                    }
                    </div>
                </td>

samedi 5 novembre 2016

how to create a link in one page that when you click on. will change another page

i'm using mvc.net and i would like to create a links in my homepage that when i click on, will changes some information in the about page. and of curse moves me to the about page. i tried to create an action link but it wouldn't solve the problem. tank you for the help!!!

vendredi 4 novembre 2016

Equivalent of ViewData["MenuItem.StoreMenuId"] using ViewBag? ViewBag.MenuItem.StoreMenuId doesn't work

Is it possible to convert ViewData["MenuItem.StoreMenuId"] to ViewBag? I use ViewBags to store IEnumerable<SelectListItem> so I can bind to @Html.DropdownListFor in my views. This works fine if its a simple property that isn't nested (i.e., StoreMenuId):

ViewBag:

ViewBag.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.StoreMenuId, null, "", new { @class = "form-control" })


But what if the property is nested (i.e., MenuItem.StoreMenuId)? This doesn't work:

ViewBag:

ViewBag.MenuItem.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })


What ends up working is changing ViewBag.MenuItem.StoreMenuId to ViewData["MenuItem.StoreMenuId"] This works:

ViewData:

ViewData["MenuItem.StoreMenuId"] = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })

There is no ViewData item of type 'IEnumerable

Controller

DepartmentLevel departmentlevel = new DepartmentLevel();
ViewBag.DepartmentLevel = new SelectList(db.DepartmentLevels, "DepartmentLevelId", "DepartmentLevelDesc", departmentlevel.DepartmentLevelId).OrderBy(a => a.Text);

HTML

 @Html.DropDownList("DepartmentLevel", ViewData["DepartmentLevel"] as SelectList, "All Department", new { @style = "width:200px;" })

What is the problem?.

jeudi 3 novembre 2016

Error SQLSERVER attempt to attach an auto-named database

this Error: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: An attempt to attach an auto-named database for file C:\Program Files (x86)\IIS Express\DB Report.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC

mycoding :

Help me plase .. I have problem a few day

How to generate authentication token after FormsAuthentication success in mvc 2

I'm developing MVC 2 web application. I'm using FormsAuthentication for sign in users to my application. I want to generate an authentication token after users are successfully login to the application. I have to pass that authentication token to another application. Are there any best ways to accomplish this task using MVC2(.net framework 4.0). Please help me to solve this problem.

Page Index is always 0 in devexpress gridview

Page Index is showing always zero.

I have implemented the Grid like the below Url: http://ift.tt/2egNxTW

and in the above url User's issue is resolved by using the below line of code
ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder(); (in Global.asax.cs) but it did not work for me.

Implementation is not exactly the same like in the above link provided but overall it is same.

@{

Html.EnableClientValidation();

Html.EnableUnobtrusiveJavaScript();

    var grid = Html.DevExpress().GridView(settings => {

        settings.Name = "GridView1";

        settings.KeyFieldName = "StudentId";

        settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };

        settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };

        settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };

        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
        settings.SettingsBehavior.ConfirmDelete = true;

        settings.SettingsPager.PageSize = 20;


        settings.CommandColumn.Visible = true;
        settings.CommandColumn.ShowNewButton = true;
        settings.CommandColumn.ShowDeleteButton = true;
        settings.CommandColumn.ShowEditButton = true;

        settings.SettingsPager.PageSizeItemSettings.Visible = true;
        settings.SettingsPager.PageSizeItemSettings.Items = new string[] { "10", "20" };

        settings.SettingsCookies.Enabled = true;
        settings.SettingsCookies.CookiesID = settings.Name;
        settings.SettingsCookies.StoreColumnsVisiblePosition = true;
        settings.SettingsCookies.StoreColumnsWidth = true;
        settings.SettingsCookies.StoreFiltering = true;
        settings.SettingsCookies.StoreGroupingAndSorting = true;
        settings.SettingsCookies.StorePaging = true;

        settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
        settings.Settings.ShowColumnHeaders = true;
        settings.Settings.ShowFilterRow = true;
        settings.Settings.ShowFilterRowMenu = true;
        settings.Settings.ShowFooter = true;
        settings.Settings.ShowGroupButtons = true;
        settings.Settings.ShowGroupedColumns = true;
        settings.Settings.ShowGroupPanel = true;
        settings.Settings.ShowHeaderFilterButton = true;
        settings.Settings.ShowTitlePanel = true;
        settings.Settings.UseFixedTableLayout = true;

        settings.HtmlRowPrepared = (s, e) =>
        {
            MVCxGridView g = s as MVCxGridView;
            var index = g.PageIndex;

        };
        settings.CustomBindingRouteValuesCollection.Add(
       GridViewOperationType.Paging,
       new { Controller = "CustomBinding", Action = "MyPagingAction" }
   );

        settings.CustomBindingRouteValuesCollection.Add(
        GridViewOperationType.Sorting,
        new { Controller = "CustomBinding", Action = "MySortingAction" }
    );


        settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
        settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
        settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
        settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
        settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;


        settings.Columns.Add("StudentName");
        settings.Columns.Add("StudentAge");
        settings.Columns.Add("StudentGrade");
        settings.Columns.Add("StudentAddress");


        settings.CellEditorInitialize = (s, e) =>
        {
            ASPxEdit editor = (ASPxEdit)e.Editor;
            editor.ValidationSettings.Display = Display.Dynamic;

        };
            });
        if (ViewData["EditError"] != null){
        grid.SetEditErrorText((string)ViewData["EditError"]);
        }
}
@grid.BindToCustomData(Model).GetHtml()

Please suggest

mercredi 2 novembre 2016

CSHTML Redirect to Another CSHTML

I am new to MVC and working on my own project. I have a small question regarding redirect to another page. Now the CSHTML is in same view folder. I am passing some data from SQL so every click has a different parameter. How do I set it to where the CSHTML knows to change the parameter itself.

CSHTML

@Html.ActionLink(Html.DisplayFor(modelItem => item.PlayerName).ToHtmlString(), "Details", new { sortOrder = ViewBag.BrandSortParm }) <br />

This only gets me to main page without the parameter of the specific record.

'The network path was not found' every first attempt to Azure SQL Server

I am developing a web application, using Visual Studio 2013 and a SQL SERVER database created on Azure.

Almost every time that I took more than 30 seconds to build and re-run the application (F5) I get this error below. The connection sql connection to SQL Timed-out and this is the error raised.

[Win32Exception (0x80004005): The network path was not found]

I retry the connection and the problem goes away. The point is that I am loosing so much time on this issue.

I have two SQL connections, to the same server, one for OWIN context, and another used by Entity Framework 6. Both MARS enable.

What I tried:

  • Disabled AVG Components
  • Disabled Windows Firewall for Home/Enterprise networks
  • Changed my dns to Google's dns (8.8.8.8/8.8.4.4), if I open nslookup and try to resolve my database path, it works every time.
  • Changed my sql connection parameters: "Connection Timeout=3;ConnectRetryCount=3;ConnectRetryInterval=1", so it takes less time to raise the error, and I can retry faster and not loose so much time.

Azure doesn't permit me "pinging" the server, since never returns. So, I am really in trouble on how to troubleshoot/monitor this issue.

Any suggestions on how to troubleshoot this are appreciated.

Getting exception StartEdit on DevExpress Grid

I have a patial view with following code(with custom data binding):

Partial View @{

Html.EnableClientValidation();

Html.EnableUnobtrusiveJavaScript();

    var grid = Html.DevExpress().GridView(settings => {
        settings.Name = "GridView1";
        settings.KeyFieldName = "StudentId";
        settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };

        settings.CustomActionRouteValues = new { Controller = "Editing", Action = "ChangeEditModePartial" };

        settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };

        settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };
        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
        settings.SettingsBehavior.ConfirmDelete = true;
        settings.SettingsPopup.EditForm.Width = 600;

        settings.CommandColumn.Visible = true;
        settings.CommandColumn.ShowNewButton = true;
        settings.CommandColumn.ShowDeleteButton = true;
        settings.CommandColumn.ShowEditButton = true;


        settings.CustomBindingRouteValuesCollection.Add(
       GridViewOperationType.Paging,
       new { Controller = "MyController", Action = "MyPagingAction" }
   );

        settings.CustomBindingRouteValuesCollection.Add(
        GridViewOperationType.Sorting,
        new { Controller = "MyController", Action = "MySortingAction" }
    );
        settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
        settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
        settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
        settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
        settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;


        settings.Columns.Add("StudentId");
        settings.Columns.Add("StudentName");
        settings.Columns.Add("StudentAge");
        settings.Columns.Add("StudentGrade");
        settings.Columns.Add("StudentAddress");

        settings.PreRender = (sender, e) =>
        {

            ((MVCxGridView)sender).StartEdit(0);/**//This is the Exception line**
        };
        settings.CellEditorInitialize = (s, e) =>
        {
            ASPxEdit editor = (ASPxEdit)e.Editor;
            editor.ValidationSettings.Display = Display.Dynamic;

        };
            });
        if (ViewData["EditError"] != null){
        grid.SetEditErrorText((string)ViewData["EditError"]);
    }
}
@grid.BindToCustomData(Model).GetHtml()///Custom binding

Please suggest the solutions:

Exception: A primary key field specified via the KeyFieldName property is not found in the underlying data source. Make sure the field name is spelled correctly. Pay attention to the character case.

mardi 1 novembre 2016

How to DownLoad Mail Attachment by using EWS in Exchange

I am using ASP.Net MVC.

using (ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding())
            {
                ICredentials creds = new NetworkCredential("username", "password");
                exchangeServer.Credentials = creds;
                exchangeServer.Url = "http://ift.tt/2e0ZAJw";

                FindItemType findItemRequest = new FindItemType();
                findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

                // define which item properties are returned in the response
                ItemResponseShapeType itemProperties = new ItemResponseShapeType();
                itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
                findItemRequest.ItemShape = itemProperties;

                // identify which folder to search
                DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
                folderIDArray[0] = new DistinguishedFolderIdType();
                folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

                // add folders to request
                findItemRequest.ParentFolderIds = folderIDArray;

                // find the messages
                FindItemResponseType findItemResponse = exchangeServer.FindItem(findItemRequest);

                // read returned
                FindItemResponseMessageType folder = (FindItemResponseMessageType)findItemResponse.ResponseMessages.Items[0];
                ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
                folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
                ItemType[] items = folderContents.Items;

                // if no messages were found, then return null -- we're done
                if (items == null || items.Count() <= 0)
                { return null; }


                // FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
                BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
                for (int i = 0; i < items.Count(); i++)
                {
                    itemIds[i] = items[i].ItemId;
                }


                GetItemType getItemType = new GetItemType();
                getItemType.ItemIds = itemIds;
                getItemType.ItemShape = new ItemResponseShapeType();
                getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
                getItemType.ItemShape.BodyType = BodyTypeResponseType.HTML;
                getItemType.ItemShape.BodyTypeSpecified = true;

                GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemType);
                ItemType[] messages = new ItemType[getItemResponse.ResponseMessages.Items.Count()];
                List<MailRecipientModel> model = new List<MailRecipientModel>();
                for (int j = 0; j < messages.Count(); j++)
                {
                    messages[j] = ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[j]).Items.Items[0];
                    MailRecipientModel model1 = new MailRecipientModel();

                    model1.Subject = messages[j].Subject;
                    model1.FromAddress = messages[j].Sender.Item.EmailAddress;
                    model1.DisplayName = messages[j].Sender.Item.Name;
                    model1.Date = messages[j].DateTimeReceived.Date.ToString();
                    model1.MailBody = messages[j].Body.Value;
                    model1.MsgId = messages[j].ItemId.Id;
                    if (messages[j].Attachments != null) {
                     //
                    }
                    model.Add(model1);
                }              

                return model;
            }

This my code I wanna download attachment file and if attachment file is image so its display in browser.

I am using Microsoft ActiveSync Exchange Server.

If you know how to do so please help me.

How replace '~' symbol in MVC with physical path

In Mvc application if the Layout is added with

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery") .

Need a solution to replace the

~

symbol .So that Output should not be like /Content/themes/base/jquery.ui.core.css in render page .

Instead

localhost:xxxxx/Content/themes/base/jquery.ui.core.css .

This Localhost need to be added when mvc application is run under IISExpress wherein It get modified to hosted application path when hosted into the server