程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了方法或操作未执行错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决方法或操作未执行错误?

开发过程中遇到方法或操作未执行错误的问题如何解决?下面主要结合日常开发的经验,给出你关于方法或操作未执行错误的解决方法建议,希望对你解决方法或操作未执行错误有所启发或帮助;

我在尝试从动态 crm 获取动态数据然后将结果转换为 Json 并使用合并一词从 crm 合并 Json 数据并生成 pdf 文件以下载时遇到问题 我在“document.SaveAs( wordDocPath);"我正在寻找这个错误,我找到了这个解决方案来删除 throw new NotImplementedException();但我的代码中没有这一行,请提供任何帮助。

namespace Propertyproseef_Tenant
{
    public partial class PropertyLease_Merger : System.Web.UI.Page
    {
        public static IOrganizationservice service = BaseModel.Getservice();
        private XrmserviceContext xrm = new XrmserviceContext(servicE);

        protected voID Page_Load(object sender,EventArgs E)
        {
            if (!IsPostBACk)
            {
                try
                {
                    String _LeasEID = request.queryString["LeasEID"];
                    //String _ProjectID = request.queryString["ProjectID"];
                    String _Type = request.queryString["Type"];

                    if ((_LeasEID != null && _LeasEID != "") && (_Type != null && _Type != ""))
                    {

                        Entity _leaseResults = LeaseResults(new GuID(_LeasEID));

                        //var _leaseResults = (from x in xrm.advanced_propertycontractSet
                        //             where x.ID == new GuID(_LeasEID)
                        //             SELEct X).FirstOrDefault();


                        var serializer = new JavaScriptserializer();
                        String Json = serializer.serialize(_leaseResults);
                        //String _Json = JsonConvert.serializeObject(_leaseResults.Attributes);


                        //JArray Json = JArray.Parse(_Json);
                        //_Json = _Json.replace("\"","").replace("[","").replace("]","").replace(",","");
                        //JObject Json = JObject.Parse(_leaseResults.Attributes.ToString());
                        


                        EntityReference projectID = null;
                        //if (_leaseResults.PropertyID != null)
                        //    projectID = new EntityReference("advanced_project",new GuID(_leaseResults.PropertyID));
                        if (_leaseResults.Attributes.Contains("blser_property"))
                            projectID = (EntityReferencE)_leaseResults["blser_property"];


                        //var projectID = Lease.blser_Property;
                        //var projectID = new EntityReference("advanced_project",new GuID(_leaseResults["blser_property"].ToString()));//_leaseResults["blser_property"].ToString();

                        var Template = (from l in xrm.blser_propertytemplateSet
                                        where l.blser_RelatedProperty.ID == projectID.ID && l.blser_Type == new OptionSETVALue(int.Parse(_TypE))
                                        SELEct l).SingLeorDefault();

                        var Notes = (from i in xrm.AnnotationSet
                                     where i.objectID.ID == Template.ID
                                     SELEct i).SingLeorDefault();

                        var filename = Notes.filename;
                        var DocBody = Convert.FromBase64String(Notes.documentBody);


                        httpPostedfileBase objfile = (httpPostedfileBasE)new MemoryPostedfile(DocBody);
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        Merger.Mergedocument(objfile,Json,".docx",fileName);
                        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////



                        //GuID LeadID = service.Create(leads);
                        //Response.StatusCode = 200;
                        //Response.Write(Json.ToString());
                    }
                    else
                    {
                        //Response.StatusCode = 401;
                        Response.Write("There are no information");
                    }
                }
                catch (Exception eX)
                {
                    //Response.StatusCode = 401;
                    Response.Write(ex.messagE);
                }
            }

        }

        private Entity LeaseResults(GuID leasEID)
        {
            String lease = String.Format(@"<fetch version='1.0' output-format='xml-platform' mapPing='logical' disTinct='false'>
                                            <entity name='advanced_propertycontract'>
                                            <all-attributes />              
                                            <order attribute='advanced_name' descending='false'/>
                                            <filter type='and'>
                                            <condition attribute='advanced_propertycontractID' operator='eq' uitype='advanced_propertycontract' value='" + leasEID.ToString() + "'/>" +
                                            @"</filter>
                                            </entity>
                                            </fetch>");

            EntityCollection Lease_Result = service.RetrIEveMultiple(new FetchExpression(leasE));

            Entity _lease = null;

            if (Lease_Result.EntitIEs.Count != 0)
            {
                _lease = Lease_Result.EntitIEs[0];
            }

            return _lease;
        }

        public class MemoryPostedfile : httpPostedfileBase
        {
            private Readonly byte[] fileBytes;

            public MemoryPostedfile(byte[] fileBytes,String filename = null)
            {
                this.fileBytes = fileBytes;
                this.filename = filename;
                this.inputStream = new MemoryStream(fileBytes);
            }

            public overrIDE int ContentLength => fileBytes.Length;

            public overrIDe String filename { get; }

            public overrIDe Stream inputStream { get; }
        }

        public class Merger
        {
            /// <sumMary>
            ///  Merge Word documents with dynamic data.
            /// </sumMary>
            /// <param name="document">A microsoft word document.</param>
            /// <param name="JData">A Json String contains data as a key-value pairs (Dictionary),a key represents a mergefIEld name in the document .. 
            /// Note : a mergefIEld name that will be replaced with image optionally can include image dimensions with as => "@w=[wIDth in pixels];@h=[height in pixel];" ..
            /// An example of an image mergefIEld name "!img@w=30;@h=50;"  where "!" is the ImageFIEldsIDentifIEr. 
            /// </param>
            /// <returns>A generated pdf file in a form of array of bytes,returns null if something went wrong.</returns>
            public static dynamic Mergedocument(httpPostedfileBase document,String JData,String Type,String fileName)
            {
                #region Variables Region
                // Declare variables
                Random random = new Random();
                List<WordDoctableFIEld> tableFIElds = new List<WordDoctableFIEld>();
                Microsoft.office.Interop.Word.Application objWord = null;
                document objDoc = null;
                dynamic NA = System.Type.Missing,TRUE = true,falSE = false,docPath;
                bool success = false,addNewRows = false;
                char ImageFIEldsIDentifIEr = WebConfigurationManager.AppSetTings["ImageFIEldsIDentifIEr"][0];
                char tableFIEldsIDentifIEr = WebConfigurationManager.AppSetTings["tableFIEldsIDentifIEr"][0];
                char columnDataSeparator = WebConfigurationManager.AppSetTings["columnDataSeparator"][0];
                String wordDocPath = HosTingEnvironment.MapPath("~") + @"\temp" + random.Next(1000) + filename.SubString(filename.LasTindexOf('.'));
                String imgPath = HosTingEnvironment.MapPath("~") + @"\temp" + random.Next(1000) + ".png";
                String pdfPath = HosTingEnvironment.MapPath("~") + @"\temp" + random.Next(1000) + ".pdf";
                String cellText = null,fIEldname = null,errormessage = null;
                int t = 1,c,r;
                #endregion

                try
                {
                    //creaTing the object of application class  
                    objWord = new Microsoft.office.Interop.Word.Application();

                    //creaTing the object of document class  
                    objDoc = new document();

                    //deserialize Data
                    Dictionary<String,String> keyvaluePairs = JsonConvert.DeserializeObject<Dictionary<String,String>>(JData);

                    // temp saving for document
                    **document.SaveAs(wordDocPath);**

                    // specify document path to word app
                    docPath = wordDocPath;

                    //open Word file document
                    objDoc = objWord.documents.Open(ref docPath,ref NA,ref falSE,ref NA);

                    #region fill table FIElds
                    // keep tables fIElds that will be filled with data
                    foreach (Microsoft.office.Interop.Word.table table in objDoc.tables)
                    {
                        r = 1;
                        foreach (Microsoft.office.Interop.Word.Row row in table.Rows)
                        {
                            c = 1;
                            foreach (Microsoft.office.Interop.Word.Cell cell in row.Cells)
                            {
                                if (cell.Range.FIElds.Count > 0)
                                {
                                    Microsoft.office.Interop.Word.Range range = cell.Range.FIElds.Parent;
                                    cellText = range.Text;
                                    // loop to be able to catch all fIElds in a cell
                                    for (int i = 1; i <= cell.Range.FIElds.Count; i++)
                                    {
                                        // handle only merge fIElds
                                        if (cellText.Contains("«") && cellText.Contains("»"))
                                        {
                                            fIEldname = cellText.SubString(cellText.IndexOf("«") + 1);
                                            fIEldname = fIEldname.SubString(0,fIEldname.IndexOf("»"));
                                            if (fIEldname.StartsWith(tableFIEldsIDentifIEr.ToString()))
                                            {
                                                tableFIElds.Add(new WordDoctableFIEld()
                                                {
                                                    FIEldname = fIEldname,tablenumber = t,Rownumber = r,columnnumber = c
                                                });
                                            }
                                            // subString to reach next fIEld
                                            if (i != cell.Range.FIElds.Count)
                                            {
                                                cellText = cellText.SubString(cellText.IndexOf("»") + 1);
                                            }
                                        }
                                    }
                                }
                                c++;
                            }
                            r++;
                        }
                        t++;
                    }


                    // filling table with data
                    t = 1;
                    foreach (Microsoft.office.Interop.Word.table table in objDoc.tables)
                    {
                        // check if a table has fIElds to be filled
                        var fIElds = tableFIElds.Where(f => f.tablenumber == t).orderBy(f => f.columnnumber).ToList();
                        if (fIElds.Count > 0)
                        {
                            // get table row that holds fIElds
                            Microsoft.office.Interop.Word.Row row = table.Rows[fIElds[0].Rownumber];
                            // fill data for each fIEld
                            foreach (var fIEld in fIElds)
                            {
                                // check for existance of table's fIEld data
                                var KVPair = keyvaluePairs.Where(d => d.Key == fIEld.FIEldName).FirstOrDefault();
                                if (!KVPair.Equals(default(keyvaluePair<String,String>)))
                                {
                                    // table column separated data
                                    var columnData = KVPair.Value.Split(columnDataSeparator);
                                    // add new rows for first table column only
                                    if (!addNewRows)
                                    {
                                        row.SELEct();
                                        Microsoft.office.Interop.Word.SELEction SELEction = objWord.SELEction;
                                        SELEction.copy();
                                        foreach (var cell in columnData)
                                        {
                                            SELEction.Paste();
                                        }
                                        addNewRows = true;
                                    }

                                    //handle image in a table cell
                                    if (fIEld.FIEldname.StartsWith(tableFIEldsIDentifIEr.ToString() + ImageFIEldsIDentifIEr))
                                    {
                                        for (int i = 0; i < columnData.Length; i++)
                                        {
                                            // replace SELEcted fIEld with Image.
                                            Microsoft.office.Interop.Word.Cell cell = table.Cell(i + fIEld.Rownumber,fIEld.columnnumber);
                                            cell.SELEct();
                                            cell.Range.Text = "";
                                            file.WriteallBytes(imgPath,Convert.FromBase64String(columnData[i]));
                                            Inlineshape Image = objWord.SELEction.Range.Inlineshapes.AddPicture(imgPath,ref TRUE);
                                            // set image wIDth and height if specifIEd in a key name
                                            float? w = GetDimensionValue(KVPair.Key,'w');
                                            float? h = GetDimensionValue(KVPair.Key,'h');
                                            if (w != null)
                                                Image.WIDth = w.Value;
                                            if (h != null)
                                                Image.Height = w.Value;
                                            //delete image from file system
                                            file.delete(imgPath);
                                        }
                                    }
                                    // handle normal table cells
                                    else
                                    {
                                        // set column data
                                        for (int i = 0; i < columnData.Length; i++)
                                        {
                                            Microsoft.office.Interop.Word.Cell cell = table.Cell(i + fIEld.Rownumber,fIEld.columnnumber);
                                            fIEldname = "«" + fIEld.FIEldname + "»";
                                            cell.Range.Text = cell.Range.Text.replace(fIEldname,columnData[i]);
                                            cell.WorDWrap = true;
                                            cell.Range.Text = cell.Range.Text.replace('\a',' ').replace('\r',' ');

                                        }
                                    }
                                }
                            }
                            //delete the placeholder row
                            row.delete();
                        }
                        t++;
                    }
                    #endregion

                    #region fill document normal fIElds (not a table multivalued ones)

                    // Mail merge object carry all document's merge fIElds
                    MailMerge mailMerge = objDoc.MailMerge;

                    foreach (MailMergeFIEld fIEld in mailMerge.FIElds)
                    {
                        keyvaluePair<String,String> keyvaluePair = keyvaluePairs.FirstOrDefault(KV => fIEld.Code.Text.Contains(" " + KV.Key + " "));
                        if (!keyvaluePair.Equals(default(keyvaluePair<String,String>)))
                        {
                            fIEld.SELEct();
                            // image fIElds
                            if (keyvaluePair.Key.StartsWith(ImageFIEldsIDentifIEr.ToString()))
                            {
                                // replace SELEcted fIEld with Image.
                                file.WriteallBytes(imgPath,Convert.FromBase64String(keyvaluePair.value));
                                Inlineshape Image = objWord.SELEction.Range.Inlineshapes.AddPicture(imgPath,ref TRUE);

                                // set image wIDth and height if specifIEd in a key name
                                float? w = GetDimensionValue(keyvaluePair.Key,'w');
                                float? h = GetDimensionValue(keyvaluePair.Key,'h');
                                if (w != null)
                                    Image.WIDth = w.Value;
                                if (h != null)
                                    Image.Height = w.Value;

                                //delete the placeholder fIEld from document
                                fIEld.delete();
                                file.delete(imgPath);
                            }
                            //normal fIElds
                            else
                            {
                                // replace SELEcted fIEld with supplIEd value.
                                objWord.SELEction.TypeText(keyvaluePair.value);
                            }
                        }
                    }
                    #endregion

                    // saving changes
                    objDoc.Save();

                    // temp saving word document as pdf
                    if (Type == ".pdf")
                        objDoc.ExportAsFixedFormat(pdfPath,WdExportFormat.wdExportFormatpdf);

                    //inDicate that all processes are succeded
                    success = true;
                }
                catch (Exception eX)
                {
                    errormessage = ex.message;
                }
                finally
                {
                    //closing document object   
                    if (objDoc != null)
                        ((_document)objDoC).Close(ref falSE);

                    //Quit application object to end process  
                    if (objWord != null)
                        ((_Application)objWord).Quit();

                    // force garbage collector to end word process
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                if (success)
                {
                    byte[] output;
                    // load pdf file
                    if (Type == ".pdf")
                        output = file.ReadAllBytes(pdfPath);
                    // load docx file
                    else
                        output = file.ReadAllBytes(wordDocPath);

                    // delete temp saved word document
                    if (file.Exists(wordDocPath))
                        file.delete(wordDocPath);
                    //delete temp saved pdf file from file system
                    if (file.Exists(pdfPath))
                        file.delete(pdfPath);

                    // return pdf file as an array ob bytes
                    return output;
                }
                // returns null if anything went wrong
                else
                {
                    // delete temp saved word document
                    if (file.Exists(wordDocPath))
                        file.delete(wordDocPath);
                    //delete temp saved pdf file from file system
                    if (file.Exists(pdfPath))
                        file.delete(pdfPath);

                    return errormessage;
                }
            }

            public static float? GetDimensionValue(String fIEldname,char dimension)
            {
                String Pattern = "@" + dimension + "=";
                if (fIEldname.Contains(Pattern))
                {
                    fIEldname = fIEldname.SubString(fIEldname.IndexOf(Pattern));
                    if (fIEldname.Contains(";"))
                    {
                        fIEldname = fIEldname.SubString(Pattern.Length,fIEldname.IndexOf(";") - Pattern.Length);
                        float dim;
                        if (float.TryParse(fIEldname,out dim))
                            return dim;
                    }
                }
                return null;
            }
        }

        // A Template/Blueprint model For MSWord document table FIElds
        public class WordDoctableFIEld
        {
            public String FIEldname { get; set; }
            public int tablenumber { get; set; }
            public int columnnumber { get; set; }
            public int Rownumber { get; set; }
        }


    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的方法或操作未执行错误全部内容,希望文章能够帮你解决方法或操作未执行错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: