Upload File to SharePoint Document Library Using the ASP.NET FileUpload Control

Recently I needed to create a Web Part that included the following:
  • A Master / DetailsView form that integrates with an external database.
  • A way to show existing documents and add new documents (and column metadata) to an existing SharePoint Document Library.
After some research I figured out how to do this by converting the FileUpload control and a ASP.NET Button control which does the actual uploading. In a nutshell you convert the posted file to a byte array and then use the SharePoint OM to upload the file. I have included the following functionality:
  • Overwrite File - You have the option of overwriting existing files or creating a new version if you have versioning turned on for the Document Library. 
  • Include Subfolders - This is done by passing a slash delimited string relative to the Document Library.
  • Update Column Metadata - This is done by passing a Dictionary<string, string> object that includes a key which is the column name and value as the value.
There is a probably a little more work I need to do to make this more bullet-proof, but it should give you a start. You can also combine it to do multiple files using my previous post: Upload Multiple Files With ASP.NET. Note: I have abbreviated the code below for brevity.
ASP.NET
<asp:FileUpload ID="fileBrowse" runat="server" />
<asp:Button ID="fileUpload" runat="server" Text="Upload Files" OnClick="fileUpload_Click" />
Code Behind:
protected void fileUpload_Click(object sender, EventArgs e)
{
    if (fileBrowse.PostedFile != null)
    {
        string siteUrl = @"http://myportal/teamsite";
        string docLibraryName = "Shared Documents";
        string folderPath = "2008/01";
        string fileName = Path.GetFileName(fileBrowse.PostedFile.FileName);
        byte[] fileBytes = GetFileBytes();
        Dictionary<string, string> columnValues = new Dictionary<string, string>();
        columnValues.Add("Document Type", "Financial");
        columnValues.Add("Author", "Mr. Burns");
        UploadFile(siteUrl, docLibraryName, folderPath, fileName, fileBytes, columnValues, true);
    }
}
public byte[] GetFileBytes()
{
    Stream stream = fileBrowse.PostedFile.InputStream;
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, (int)stream.Length);
    stream.Close();
    return bytes;
}
public void UploadFile(string siteUrl, string docLibraryName, string folderPath,
    string fileName, byte[] fileByteArray, Dictionary<string, string> columnValues, bool overWrite)
{
    try
    {
        string fileUrl = siteUrl.EnsureEndSlash() + docLibraryName.EnsureEndSlash() +
            folderPath.EnsureEndSlash() + fileName;
        string currentFolder = siteUrl.EnsureEndSlash() + docLibraryName.EnsureEndSlash();
        using (SPWeb web = new SPSite(siteUrl).OpenWeb())
        {
            web.AllowUnsafeUpdates = true;
            SPFolder folder = web.Folders[docLibraryName];
            if (folderPath != string.Empty)
            {
                foreach (string subFolder in folderPath.Split('/'))
                {
                    currentFolder = currentFolder.EnsureEndSlash() + subFolder;
                    if (!web.GetFolder(currentFolder).Exists)
                    {
                        folder.SubFolders.Add(subFolder);
                    }
                    folder = folder.SubFolders[subFolder];
                }
            }
            if (overWrite || !web.GetFile(fileUrl).Exists)
            {
                folder.Files.Add(fileName, fileByteArray, true);
            }
            else
            {
                folder.Files[fileName].CheckOut();
                folder.Files.Add(fileName, fileByteArray, true);
                folder.Files[fileName].CheckIn(String.Empty);
            }
            SPFile file = folder.Files[fileUrl];
            foreach (KeyValuePair<string, string> columnValue in columnValues)
            {
                file.Item.Properties[columnValue.Key] = columnValue.Value;
            }
            file.Item.Update();
        }
    }
    catch (Exception ex)
    {
        //TODO: Add Exception Handling
    }
}

Create Dictionary

 static Dictionary<string, int> roles = new Dictionary<string, int>();

 public static Dictionary<string, int> SetRoles(List<string> items)
           {
               if (roles != null)
               {
                   roles.Clear();
               }
               foreach (string item in items)
               {
                  // var Entitytype = item.Split('_')[1];
                   var country = item.Split('_')[2];
                  
                   string Session_osoid = db.View_SharePointMappingTable.Where(x => x.GroupName == item).FirstOrDefault().OsoID.ToString();
                   var Session_Priority = db.View_SharePointMappingTable.Where(x => x.GroupName == item).FirstOrDefault().Priority;

                   var role = item.Split('_')[3];
                   if (!roles.Keys.Contains(Session_osoid) || Session_Priority > roles[Session_osoid])
                       roles[Session_osoid] =Convert.ToInt32(Session_Priority);
               }
               return roles;
           }



Calling Dictionary


  Dictionary<string, int> roles;

  List<string> items = null;
                       
                        keyList = null;
                        priorityList = null;

                        items = Session["AuthenticateOso"].ToString().Split(',').ToList();
                        if (roles!=null)
                        {
                            roles.Clear();
                        }
                        roles = Appcommon.SetRoles(items);
                        var OsoidList = roles.Keys;
                        var Priority = roles.Values.ToArray();
                        keyList = roles.Keys.ToArray();

                        priorityList = Priority;

Linq Save and Update Query

#region ButtonSave
        protected void btnsave_Click(object sender, EventArgs e)
        {

          

            if (Code != String.Empty && !string.IsNullOrEmpty(Code))
            {
                if (UpdateAccounts())
                {
                    mvMarketFactors.ActiveViewIndex = 0;
                    msgWarning.Visible = true;
                    lblmessage.Text = "Successfully Updated";
                    BindGrid();
                }
            }
            else
            {

                if (SaveAccounts())
                {
                    mvMarketFactors.ActiveViewIndex = 0;
                    msgWarning.Visible = true;
                    lblmessage.Text = "Successfully Inserted";
                    BindGrid();

                }
            }


        }
        #endregion

        #region SaveAccounts
        private bool SaveAccounts()
        {
            bool flag = true;
            var osoID = Convert.ToInt32(ddlOso.SelectedValue);
            var ManagersID = Convert.ToInt32(ddlManagers.SelectedValue);

            TcaManager TcaManagersID = db.TcaManagers.Where(x => x.TcaManagerID == ManagersID).FirstOrDefault();
            MstrOSoOfficesMarket OsoID = db.MstrOSoOfficesMarkets.Where(x => x.OSOOfficesMarketsPkID == osoID).FirstOrDefault();

            MarketFactor tbl = new MarketFactor();

            tbl.Title = txtTitle.Text.Trim();
            tbl.Summary = txtSummary.Text.Trim();
            tbl.Details = txtDetails.Text.Trim();
            if (RBIsPositiveYes.Checked == true)
            {
                tbl.IsPositive = 1;
            }
            else
            {
                tbl.IsPositive = 0;
            }
            if (RByes.Checked == true)
            {
                tbl.IsActive = 1;
            }
            else
            {
                tbl.IsActive = 0;
            }

            tbl.MstrOSoOfficesMarket = OsoID;
            tbl.TcaManager = TcaManagersID;

            tbl.CreatedBy = Session["LoginUser"].ToString();
            tbl.IsDeleted = 0;
            tbl.CreatedDate = DateTime.UtcNow;

            db.AddToMarketFactors(tbl);
            db.SaveChanges();

            var attachmentMarketFactorsID = 0;
            attachmentMarketFactorsID = tbl.MarketFactorsPkID;
            var filepkID = 0;
            AddAttachments(filepkID, attachmentMarketFactorsID);
            return flag;
        }
        #endregion

#region UpdateAccounts
        private bool UpdateAccounts()
        {

            bool flag = true;

            var MarketFactorsPkID = Convert.ToInt32(Code);
            var osoID = Convert.ToInt32(ddlOso.SelectedValue);
            var ManagersID = Convert.ToInt32(ddlManagers.SelectedValue);

            MarketFactor tbl = db.MarketFactors.First(i => i.MarketFactorsPkID == MarketFactorsPkID);

            tbl.Title = txtTitle.Text.Trim();
            tbl.Summary = txtSummary.Text.Trim();
            tbl.Details = txtDetails.Text.Trim();
            if (RByes.Checked == true)
            {
                tbl.IsActive = 1;
            }
            else
            {
                tbl.IsActive = 0;
            }

            TcaManager TcaManagersID = db.TcaManagers.Where(x => x.TcaManagerID == ManagersID).FirstOrDefault();
            MstrOSoOfficesMarket OsoID = db.MstrOSoOfficesMarkets.Where(x => x.OSOOfficesMarketsPkID == osoID).FirstOrDefault();
            tbl.MstrOSoOfficesMarket = OsoID;
            tbl.TcaManager = TcaManagersID;

            tbl.ModifiedBy = Session["LoginUser"].ToString();
            tbl.ModifiedDate = DateTime.UtcNow;
            //Save the changes back to database.
            db.SaveChanges();
            return flag;
        }
        #endregion

Show images condition in grid list

Client side
Visible='<%# ShowImgElement(Eval("Status").ToString()) && AddelementsPermission(Eval("OsoNameID").ToString()) %>'

Server side


 #region Visible hide settings
        //status wise setting
        public bool ShowImg(string Status)
        {
            if (Status == "New")
                return true;
            else if (Status == "Approved Main Initiative")
                return false;
            else if (Status == "Completed")
                return false;
            else
                return false;
        }

        public bool ShowImgElement(string Status)
        {
            if (Status == "New")
                return true;
            else if (Status == "Approved Main Initiative")
                return true;
            else if (Status == "Completed")
                return false;
            else
                return true;
        }

Contains condition in EF Linq

 private void BindsearchOso()
        {

            if (keyList != null)
            {

                if (keyList.Contains("12") && roles["12"] > 2)
                {
                    var result = db.MstrOSoOfficesMarkets.Where(x => x.IsDeleted == 0).ToList();
                    ddlSearchOso.DataSource = result;
                }
                else
                {
                    var result = db.MstrOSoOfficesMarkets.Where(x => x.IsDeleted == 0).ToList().Where(x => keyList.Contains(x.OSOOfficesMarketsPkID.ToString())).ToList();
                    ddlSearchOso.DataSource = result;
                }

                ddlSearchOso.DataValueField = "OSOOfficesMarketsPkID";
                ddlSearchOso.DataTextField = "Name";
                ddlSearchOso.DataBind();
                ListItem l = new ListItem("Office", "0");
                ddlSearchOso.Items.Insert(0, l);
            }
        }

word-break css

word-break: break-word;
word-break: break-all;
word-break: keep-all;
word-break: normal;
word-wrap: break-word;

Contains Query in linq

 private void BindParentExpensetype()
        {

            var parent_ids = (db.MstrBudgetLines.Where(y => y.ParenetID != null).Select(x => x.ParenetID).Distinct()).ToList();
           
            var Parents = (from e1 in db.MstrBudgetLines
                           where  e1.IsDeleted==0 && e1.IsActive==1 

                           select new
                           {
                               parentid=e1.BudgetLinesPkID,
                               BudgetLinesPkID = e1.BudgetLinesPkID,
                               BudgetLinesName = e1.BudgetLinesName
                           }).ToList().Where(x=>parent_ids.Contains(x.parentid));


            ddlparentexpensetype.DataSource = Parents;
            ddlparentexpensetype.DataValueField = "BudgetLinesPkID";
            ddlparentexpensetype.DataTextField = "BudgetLinesName";
            ddlparentexpensetype.DataBind();

        }

Dropdown binding query

 private void BindtargetSegment()
        {

            var result = db.MstrTargteSegments.Where(x => x.IsDeleted == 0 && x.IsActive == "1").ToList();
            dropdowntargetsegment.DataSource = result;
            dropdowntargetsegment.DataValueField = "TargteSegmentPkID";
            dropdowntargetsegment.DataTextField = "TargetSegmentName";
            dropdowntargetsegment.DataBind();
        }

Conditional Query in linq

 var BusinessPlanID = Convert.ToInt32(ddlSearchBuisnessPlan.SelectedValue.ToString());
                var CategoryID = Convert.ToInt32(ddlSearchCategory.SelectedValue.ToString());
                var StratergicTypeID = Convert.ToInt32(ddlSearchStratergicType.SelectedValue.ToString());
                var StatusID = Convert.ToInt32(ddlSearchStatus.SelectedValue.ToString());
                var OsoId = Convert.ToInt32(ddlSearchOso.SelectedValue.ToString());

                IQueryable<View_Initiative> query = db.View_Initiative.Where(x => x.IsDeleted == 0);

                if (BusinessPlanID != 0)
                {
                    query = query.Where(p => p.BusinessPlanID == BusinessPlanID);
                }

                if (CategoryID != 0)
                {
                    query = query.Where(p => p.InitiativesCategoryID == CategoryID);
                }

                if (StratergicTypeID != 0)
                {
                    query = query.Where(p => p.StratgyTypeID == StratergicTypeID);
                }

                if (OsoId != 0)
                {
                    query = query.Where(p => p.RelatedOsoOrMarketID == OsoId);
                }

                if (StatusID != 0)
                {
                    query = query.Where(p => p.ProcessStagesID == StatusID);
                }



                var fetchedresult = query.ToList().Select(t => new
                    {
                        INITIATIVETITLE = (t.InitiativeTitle),
                        TARGETVALUE = (t.TargetValue),
                        TARGETDESCRIPTION = (t.TargetDescription),
                        FROMDATE = (t.FromDate),
                        TODATE = (t.ToDate),
                        EXPECTEDINCREMENTALBUSINESS = (t.ExpectedIncrementalBusiness),
                        REQUESTEDBUDGETBYOSO = (t.RequestedBudgetByOSO),
                        APPROVEDBUDGET = (t.ApprovedBudget),
                        InitiativesPkID = (t.InitiativesPkID),
                        KpiWeightage = (t.KpiWeight),
                        InitiativeCAtegory = (db.MstrInitiativeCategories.Where(x => x.InitiativeCategoryPkID == t.InitiativesCategoryID).FirstOrDefault().InitiativeCategoryName),
                        Status = (db.MstrProcessStages.Where(x => x.MstrProcessStagesPkID == t.ProcessStagesID).FirstOrDefault().StagesName),
                        StratergyType = (db.MstrStratergicTypes.Where(x => x.StratergicTypeID == t.StratgyTypeID).FirstOrDefault().StratergicName),
                        Businessplan = (db.BusinessPlans.Where(x => x.BusinessPlanPkID == t.BusinessPlanID).FirstOrDefault().BusinessPlanName),
                        OsoName = (db.MstrOSoOfficesMarkets.Where(x => x.OSOOfficesMarketsPkID == t.RelatedOsoOrMarketID).FirstOrDefault().Name),
                        OsoNameID = t.RelatedOsoOrMarketID
                    });

                GV_List.CurrentPageIndex = 0;
               
                GV_List.DataSource = fetchedresult;
               
                Cache["GridsearchDataSource"] = fetchedresult;
                GV_List.DataBind();

Dropdown list inserting value in 0 th position

  ddlSearchBuisnessPlan.DataValueField = "BusinessPlanPkID";
                ddlSearchBuisnessPlan.DataTextField = "BusinessPlanName";
                ddlSearchBuisnessPlan.DataBind();
                ListItem l = new ListItem("Buisness Plan", "0");
                ddlSearchBuisnessPlan.Items.Insert(0, l);

Post back event in with out refresh (Using Web method in aspx page)

 Server Side Code

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetBindBudgetlineresult(string ID)
        {
            TCA_OSOEntities context = new TCA_OSOEntities();
            

            var PID = Convert.ToInt32(ID);

            var Budgetlineresult = (from MstrBudgetLine tbl in context.MstrBudgetLines
                                    where tbl.IsDeleted == 0 && tbl.IsActive == 1 && tbl.ParenetID == PID
                                    select new
                                    {
                                        BudgetLinesPkID=tbl.BudgetLinesPkID,
                                        BudgetLinesName=tbl.BudgetLinesName

                                    }).ToList();                                     
                                       
               
           
            var jsonSerialiser = new JavaScriptSerializer();
            var jsonresult = jsonSerialiser.Serialize(Budgetlineresult);

            return jsonresult;
        }

Client Side Code

    function ddlparentexpensetype_SelectedIndexChanged(sender, args) {
                // To get the item 
                var item = args.get_item();
                //To get the item text
                var itemText = args.get_item()._text;

                BindBudgetline();

            }

***********************************************


        function BindBudgetline() {
            
            $.ajax({
                type: "POST",
                url: "AddInitiative.aspx/GetBindBudgetlineresult",
                data: '{ID: "' + document.getElementById("<%= ddlparentexpensetype.ClientID %>").control._value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnBudgetlineSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }
        function OnBudgetlineSuccess(response) {
          
            var data = JSON.parse(response.d);
            if (data.length != 0) {

                var drop = $find('<%=dropdownbudgetline.ClientID %>');
                drop.clearItems();
                drop.set_text("");

                for (var i = 0; i < data.length; i++) {

                    var combo = $find("<%= dropdownbudgetline.ClientID %>");
                    var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                    comboItem.set_text(data[i]["BudgetLinesName"]);
                    combo.set_value(data[i]["BudgetLinesPkID"]);
                    combo.trackChanges();
                    combo.get_items().add(comboItem);
                    comboItem.select();
                    combo.commitChanges();
                }
            }
            else {

                var drop = $find('<%=dropdownbudgetline.ClientID %>');
                drop.clearItems();
                drop.set_text("");
            }
        }

        /* End*/

        function AmountConvertions() {

            $.ajax({
                type: "POST",
                url: "AddInitiative.aspx/GetConvertedAmount",
                data: "{ 'Amt': '" + document.getElementById("<%= txtrequestedbudgetbyoso.ClientID %>").value + "', 'Osoid': '" + document.getElementById("<%= dropdownoso.ClientID %>").control._value + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnAmountConvertionsSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

event.preventDefault()

Description: If this method is called, the default action of the event will not be triggered.


Example:

Cancel the default action (navigation) of the click.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.preventDefault demo</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>
<script>
$( "a" ).click(function( event ) {
event.preventDefault();
$( "<div>" )
.append( "default " + event.type + " prevented" )
.appendTo( "#log" );
});
</script>
</body>
</html>

Search This Blog

Arsip Blog

Powered by Blogger.

Recent

Comment

Author Info

Like This Theme

Popular Posts

Video Of Day

Sponsor

Most Popular