Category Archives: DynamicEntity

[RESOLVED] Add link to report on Details.aspx

<asp:FormView runat="server" ID="FormView1" DataSourceID="DetailsDataSource" OnItemDeleted="FormView1_ItemDeleted" RenderOuterTable="false">
                <ItemTemplate>
                    <table id="detailsTable" class="DDDetailsTable" cellpadding="6">
                        <asp:DynamicEntity runat="server" />
                        <tr class="td">
                            <td colspan="2">
                                <asp:DynamicHyperLink runat="server" Action="Edit" Text="Edit" />
                                <asp:LinkButton runat="server" CommandName="Delete" Text="Delete"
                                    OnClientClick='return confirm("Are you sure you want to delete this item?");' />
                                <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/RptArcs.aspx?ContentShtNum={0}">Report</asp:HyperLink>

Could you give a little more information?  What is your question?

 

Matt

First can't I just vent about how frustrating it is when you post from one forum and it gets posted in another forum. I was in the Dynamic Data forum when I posted this. I must be missing the field that lets you specify what forum to post the thread in.

I'm using DYNAMIC DATA \ Entity Framework and I want to add a link to the Details.aspx page which uses the ID passed (in this case the field: ContentShtNum) to access a report for that id\record.

have you tried to do this

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("~/RptArcs.aspx?ContentShtNum={0}", Eval("ContentShtNum"))%>'>Report</asp:HyperLink>

Thank you perper, That works! A happy ending on a Friday afternoon - love it!

glad to hear it help you..happy weekend.. please mark the appropriate post as answer that helped you..

ASP.NET 3.5 FileUpload - stop the fiel from uploading!

Hi All,

I want to use the FileUpload control in ASP to allow a user to select a file so that I can extract the file path of the selected file. E.g. if the user pick 'C:/Windows/something.txt' I want to extract that whole path. I can do this using FileUpload1.PostedFile.Filename - not a problem.

The issue is that the file is actually uploaded when a postback occurs - I dont want it to actually post the file to the server, I simply need to extract the file path. How can i stop it from actually uploading the file?

Many thanks in advance!

 

bipulshah

I want to use the FileUpload control in ASP to allow a user to select a file so that I can extract the file path of the selected file. E.g. if the user pick 'C:/Windows/something.txt' I want to extract that whole path. I can do this using FileUpload1.PostedFile.Filename - not a problem.

only IE supports that, atleast to my knowledge...remaining browsers you cannot get that path from PostedFile...al you can do is ask user to enter that path in a textbox...or else you got to use some ActiveX on client side to make this requirement done...

Thanks,

running in IE only is fine as thats the only supported browser we use.

Asking them to enter it manually into a textvox is not an option. They need to be able to navigate to a file path using a windows style open file dialog box.

           

if (FileUpload1.HasFile)
                {

                       \\This is the filename of the file you uploaded

                        string filepath = FileUpload1.PostedFile.Filename;

                \\ For Saving the File we use FileUpload1.SaveAs(MapPath(filepath));  Just Dont add this line

                }

Hi, but the problem is, when the page is posted back (I have an 'Add' button) it beings to upload the selected file, even tho I dont have the FileUpload1.SaveAs etc...

Its not possible to upload the selected file without any codes to do so..

Do You have the code.. Please Debug to see whats going on...

If it is really uploading your file it will surely led you to the code for uploading the file..

By the way please check the path where your file is saved.. Delete all files in that folder and then check.. It might be possible that you are looking in some other folder or the path specified is not correct..

use the validation for the control...

<asp:FileUpload ID="FileUpload1" runat="server" BackColor="#CCFF66" />

 <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="FileUpload1" ErrorMessage="Please Upload PDF files" ValidationExpression="^([a-zA-Z].*|[1-9].*)\.(((p|P)(d|D)(f|F))|((d|D)(o|O)(c|C)))$" ValidationGroup="submit" Text="*"></asp:RegularExpressionValidator>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="FileUpload1"  ErrorMessage="please upload the pdf file." ValidationGroup="submit" Text="*"></asp:RequiredFieldValidator>
  <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                  ValidationGroup="submit" ShowMessageBox="True" ShowSummary="False"/>

<asp:Button id="buton1" runat="server" ValidationGroup="submit" text="Upload">
</asp:Button>



Hi again - well the page hangs and on the server it reports:

Event message: Post size exceeded allowed limits.

in the event log.

Even tho there isn't any code that specifically uploads the file. It complains that the file is too big. It works fine for small file sizes. This implies that it is trying to upload the file?

Or is it simply checking to see if that file can be uploaded and crashing out coz it's too big?

Post Your Complete Code..

If you use <input type="file" id="fileinput">

You can get filename only, as browser dont give you full path as they consider it security breach.

$("#fileinput").val(); //It will give you file name only
var filename = $('input[type=file]').val().split('\\').pop(); //It will give you file name only

See following discussions for further assistance.

http://stackoverflow.com/questions/3489133/full-path-from-file-input-using-jquery

http://stackoverflow.com/questions/740114/how-to-use-jquery-to-get-the-current-value-of-a-file-input-field

http://forums.asp.net/t/1668581.aspx/1

So limitation is that you can only get the file in javascript, so you can bind this name to some hidden field or label and clear the fileupload field.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

namespace Crm.DocumentLinkControl
{
    public partial class Default : System.Web.UI.Page
    {
        string objectTypeCode;
        string objectId;
        string fieldname;
        string orgName;
        string filepath;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private void UpdateList(BusinessEntityCollection records)
        {
            ListBox1.Items.Clear();
            if (records.BusinessEntities.Count > 0)
            {
                foreach (BusinessEntity record in records.BusinessEntities)
                {
                    DynamicEntity documentLinkRecord = (DynamicEntity)record;
                    string documentLinkId = (documentLinkRecord["documentlinkid"] as Key).Value.ToString();
                    string documentLinkUrl = documentLinkRecord["url"].ToString();
                    ListItem item = new ListItem(documentLinkUrl, documentLinkId);
                    ListBox1.Items.Add(item);
                }
            }
            else
            {
                ListBox1.Items.Clear();
            }
        }

        protected void AddBtn_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(File1.PostedFile.FileName))
            {
                using (DocumentLink dcData = new DocumentLink(orgName))
                {
                    BusinessEntityCollection records = dcData.WriteRecords(fieldname, objectId, objectTypeCode, File1.PostedFile.FileName);
                    UpdateList(records);
                }
            }
        }
    }
}

You can get the full path like:

string FullPath = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
Label1.Text = FullPath;

If user have selected a file and create a postback the file is upload to the server (in memory) if you don'd save the file the file is not saved in your root.

FileUpload1.SaveAs(MapPath(filepath));

The fileupload control is made for that


By the way where is the file getting saved?? Is there specific folder or what??

geniusvishal

By the way where is the file getting saved?? Is there specific folder or what??

With this line code yes:

FileUpload1.SaveAs(MapPath(filepath));



Primillo

With this line code yes:

FileUpload1.SaveAs(MapPath(filepath));

Hi Primillo i just asked bipul where does his file getting saved.. This guy havent used the abovesaid code.. Thats why i asked where are his file getting saved.. Is it some kind of folder or in the root directory itself..

Hi geniusvishal

I believe he don't want to save the file in the server, just need to save the full path.

bipulshah

The issue is that the file is actually uploaded when a postback occurs - I dont want it to actually post the file to the server, I simply need to extract the file path. How can i stop it from actually uploading the file?

May be he wants the full path but he also wants to stop the file from uploading thats why i asked so.. Never mind.. Cheers :-)

Hi bipul,

Why would you want to get just the file path? Most of the modern browsers do not give the file path (C:\fakepath issue). If you have leverage with your users then you can change the IE settings for not to hide the orignal path and then user jquery/javascript to access the file path from the input file control

http://stackoverflow.com/questions/4851595/how-to-resolve-the-c-fakepath

Hi, its because we want to stop ourselves from duplicating files. There is a fileshare on a server with loads of files. We want to reference these files from within MS CRM. Rather than attach the files etc to CRM which would cause duplication, all we want to do is to allow the user to pick a file using the File Open dialog and then I can take that path and store it in CRM.

Hi Vishal, i dont want to save the file. I simply want to use the FileUpload control as a way for the user to select a file from a file share. I want to take that directory and store it in a field in CRM. The point in this is to reduce/remove duplication by not creating the same document in loads of systems. Instead, store the file on a fileshare (where they are already) and create a link to this file in CRM records. I dont want to save the file, I just want a simple way for the user to select a file from the fileshare and to store that directory path.

Adding UserId to table using Model Binding

Hi everyone, I used the preinstalled Web Forms Template (.Net 4.5) and, I have a WebForms application where I'm using Modelbinding, and EntityFramework code first. All is going faily well. I am also using the built in Membership provider to handle Authentication/Authorization. After my user selects a service from my Services page, I am redirecting them to the Register page, where they will register for an account.

My question is, After they register, I am sending them to a page where they will add their personal info. I am using DynamicDataTemplates with model binding:

//here is my FormView
<div class="container">
        <div class="row">
            <div class="col-md-12">
                <hgroup class="title">
        <h1><%: Title %>.</h1>
        <h2>Use the form below to add your personal info.</h2>
    </hgroup>
            </div><!--end of col-md-12-->
        </div><!--end of row-->
    </div><!--end of container-->
    <div class="clearTop"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <div class ="container">
        <asp:FormView ID="addUserInfoForm" runat="server" ItemType="PoochiesPrix_4.Models.Owner"
        InsertMethod="addUserInfoForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addUserInfoForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity2" runat="server" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
        </asp:FormView>
    </div><!--end of container-->

My code behind that has my strongly typed fileds:

public void addUserInfoForm_InsertItem()
        {
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    db.Owners.Add(item);
                    db.SaveChanges();
                }

            }
        }
        protected void addUserInfoForm_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Response.Redirect("~/AddDog.aspx");
        }
        protected void cancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/OurServices.aspx");
        }

Since my users are registered already. How would I access their UserID in order to insert it into my owners table when they submit this form? I am new to LINQ so I am not sure how to go about this. Since I am using EF context classes, I know this ID is available to me, but, I dont know how to add it to the code above to insert it as this user who is submitting this form. I am looking for a good article to read and learn how to implement this. Any suggestions are welcomed too.

Hi,

According to your description, you want to insert data into entity model. So far as I know, please refer to the simple demo about person below:

var person = new Person { Name = "Adam" };

var db = new YourEFContext();

db.People.Add(person);

db.SaveChanges();

For more information about insert data into entity model, please refer to the link below:

http://www.dotnetcurry.com/showarticle.aspx?ID=619

Hope it's useful for you.

Best Regards,

Michelle Ge

Hi Michelle, Thank you. I already know how to insert/update data into an entity model. What I am uncertain about is, how I would insert the currently logged in Users UserId that they were assigned after they registered on the registration page?  I am using the UserId as a foriegn key in this Owners table, Si I would like to include the userId in this insert from this form.

[RESOLVED] Using Datepicker with FormView

Hi All,

I have a Web forms application using EF Code First. I am using ModelBinding, and all is going well. I decided to try my hand at DynamicDataEntities which I installed from NuGet packageManager. I have a FormView that is bound to my entity data model, and Im using the DynamicDataTemplates. I was just letting ASP build my form for me with the input fields, which worked fine, but, I need more control over the date fields. I want to add a jQuery Datepicker on the Date fields but I am having trouble.  I was using this:

 <%--I was using a DynamicDataEntiy to render my form from my Model--%>

<asp:FormView ID="addDogForm" runat="server" ItemType="PoochiesPrix_4.Models.DogInfo"
        InsertMethod="addDogForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addDogForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <%--<asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />--%>
           </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
    </asp:FormView>

This worked fine, but, In my Model:

//I have date fields that I want to show a Datepicker for

public class DogInfo
    {
        [Key, Display(Name = "DogInfoID")]
        [ScaffoldColumn(false)]
        public int DogInfoID { get; set; }

        [Required(ErrorMessage = "Name is required"), StringLength(35), Display(Name = "Dogs Name")]
        public string name { get; set; }

        [Required(ErrorMessage = "License number is required"), StringLength(15), Display(Name = "License Number")]
        public string licenseNumber { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License was Renewed")]
        [Range(typeof(DateTime), "1/1/2014", "1/1/3000", ErrorMessage = "Please provide a renewal date after 1/1/2014")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime dateLicenseRenewed { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License Expires")]
        [Range(typeof(DateTime), "1/1/2014", "1/1/3000", ErrorMessage = "Please provide a date after 1/1/2014")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime dateLicenseExpires { get; set; }

        [Display(Name = "Coat Color")]
        public string coatColor { get; set; }

        [Display(Name = "Eye Color")]
        public string eyeColor { get; set; }

        [Required(ErrorMessage = "Enter Male or Female"), StringLength(6, MinimumLength = 4), Display(Name = "Sex")]
        public string sex { get; set; }

        [Display(Name = "Breed")]
        public string breed { get; set; }

        [Required(ErrorMessage = "Required. If you do not know your dogs DOB, enter an approximate date."), Display(Name = "Birth Date")]
        public DateTime birthDate { get; set; }

        [Display(Name = "Microchip Number")]
        public string microchipNumber { get; set; }

        [Display(Name = "Breed Registration")]
        public string breedRegistration { get; set; }

        [Display(Name = "Breed Shelter Name")]
        public string breedShelterName { get; set; }

        [Display(Name = "Date Acquired")]
        [Range(typeof(DateTime), "1/1/1900", "1/1/3000", ErrorMessage = "Please an approximate date after 1/1/1900")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public Nullable<DateTime> dateAcquired { get; set; }

        [ScaffoldColumn(false)]
        public Guid OwnerID { get; set; }

        [EnumDataType(typeof(DogType)), Display(Name = "Dog Type")]
        public DogType dogType{ get; set; }


        [ScaffoldColumn(false)]
        public ICollection<DogPic> DogPics { get; set; }

        [ScaffoldColumn(false)]
        public List<Veternarian> Veternarians { get; set; }
    }
    public enum DogType
    {
        Adult,
        Puppy
    }

I have tried explicitedly adding the entities to the page in its each DynamicControl like this:

HTML:

<asp:FormView ID="addDogForm" runat="server" ItemType="PoochiesPrix_4.Models.DogInfo"
        InsertMethod="addDogForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addDogForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <%--<asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />--%>
                <asp:DynamicControl ID="DynamicControl1" runat="server" DataField="name" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl2" runat="server" DataField="licenseNumber" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl3" runat="server" DataField="dateLicenseRenewed" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl4" runat="server" DataField="dateLicenseExpires" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl5" runat="server" DataField="coatColor" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl6" runat="server" DataField="eyeColor" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl7" runat="server" DataField="sex" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl8" runat="server" DataField="breed" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl9" runat="server" DataField="birthDate" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl10" runat="server" DataField="microchipNumber" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl11" runat="server" DataField="breedRegistration" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl12" runat="server" DataField="breedShelterName" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl13" runat="server" DataField="dateAcquired" Mode="Insert" />
                 <asp:DynamicControl ID="DynamicControl14" runat="server" DataField="dogType" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
    </asp:FormView>

Then editing the DateTime_Edit.ascx, Dynamic Template mark up:

<%-- Use the Juice Datepicker--%>

<juice:Datepicker runat="server" id="t1" targetcontrolid="DynamicControl3" />
<asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox

Then in my DateTime_Edit.ascx.cs, I set a date range for my Calender:

protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.ToolTip = Column.Description;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);
            SetUpCustomValidator(DateValidator);

        //when my calendar displays, restrict the date range the user can pick.

            RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
            if (ra != null)
            {
                t1.MinDate = ra.Minimum.ToString();
                t1.MaxDate = ra.Maximum.ToString();

            }
                
        }

I am getting an error that the value is null in my calendar. I know why this is happening, because I am using EF Code first, and I am dropping and recreating my Database evertime I run my application if my Model changes. I am not sure how to set a default value in my code behind for this Calendar so that i do not get an error. I would like to set the current date as the date that displays. I believe that this will eliminate the null error too. I'm not sure though, since EF is using my database to build the form. i hope that I explained this clear enough. Iwould like some direction on how to go about setting default values on my DynamidDataTemplate fileds.

Hi,

If you want to set default date for the jQuery Datepicker, you could try:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

For more information, you could refer to:

http://stackoverflow.com/questions/14580749/jquery-datepicker-set-default-date

http://stackoverflow.com/questions/4915990/set-todays-date-as-default-date-in-jquery-ui-datepicker

Regards

Shawn,

Thanks allot for the info.It helped allot. I have all of my DatePickers working now.I found that I just needed to set each Datepicker for TexBox1 in the DynamicDataEntity Template, DateTime_Edit.ascx:

<juice:Datepicker runat="server" id="t1" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t2" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t3" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t4" targetcontrolid="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox>

Then in the DateTime_Edit.cs file, i did this:

RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
            if (ra != null)
            {
                t1.MinDate = ra.Minimum.ToString();
                t1.MaxDate = ra.Maximum.ToString();
                t2.MinDate = ra.Minimum.ToString();
                t2.MaxDate = ra.Maximum.ToString();
                t4.MinDate = ra.Minimum.ToString();
                t4.MaxDate = ra.Maximum.ToString();

            }

In my Page, I put a script:

<script type="text/javascript">
        $(function () {
            $('#t1').datepicker();
            $('#t1').datepicker('setDate', new Date());
        });
    </script>

For each one that I wanted a default date set in. Actually, when I set the targetcontrolid to "TextBox1, the page ran fine." Thanks for the links though. They are good. Cheers!