示例#1
0
文件: Program.cs 项目: weijx-xa/test
        static void offp()
        {
            var pid            = 1;
            var rid            = 1;
            var sdate          = "2016/01/01";
            var edate          = "2016/08/08";
            var input          = "{\"principal\":" + pid + ",\"receiver\":" + rid + ",\"startdate\":\"" + sdate + "\",\"enddate\":\"" + edate + "\"}";
            var app            = new MFilesClientApplication();
            var vault          = app.BindToVault("8211", IntPtr.Zero, true, true);
            var FilterReceiver = vault.ExtensionMethodOperations.ExecuteVaultExtensionMethod("GetSecureNotice", input);

            Console.WriteLine(FilterReceiver);
            //  var filedata = eval('(' + FilterReceiver + ')');
            var filedata = JsonConvert.DeserializeObject <ReportPrintData>(FilterReceiver);
            // alert(filedata.objver.id);
            // var ObjID  = MFiles.CreateInstance("ObjID");
            //   ObjID.SetIDs (0,filedata);
            var objver = new ObjVer();

            objver.SetIDs(filedata.objtype, filedata.objid, filedata.objversion);
            var filever = new FileVer();

            filever.ID      = filedata.fileid;
            filever.Version = filedata.fileversion;
            vault.ObjectFileOperations.OpenFileInDefaultApplication(IntPtr.Zero, objver, filever,
                                                                    MFFileOpenMethod.MFFileOpenMethodOpen);
        }
示例#2
0
        /// <summary>
        /// 通过库连接名称获取库
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Vault GetVaultByName(string name)
        {
            var clientApp = new MFilesClientApplication();
            var vc        = clientApp.GetVaultConnection(name);

            return(vc.BindToVault(IntPtr.Zero, true, true));
        }
示例#3
0
        /// <summary>
        /// 设置客户端MFiles连接
        /// </summary>
        /// <param name="user"></param>
        /// <param name="vault"></param>
        public static Vault GetUserVault1(UserDto user, VaultDto vault)
        {
            if (VaultGuids.Contains(vault.Guid))
            {
                return(GetVault(user, vault.Guid));
            }
            var server = vault.Server;
            var conn   = new VaultConnection();
            var domain = user.Domain;

            conn.AuthType         = MFAuthType.MFAuthTypeSpecificWindowsUser;
            conn.AutoLogin        = false;
            conn.NetworkAddress   = server.Ip;     // "192.168.2.129";
            conn.Endpoint         = server.Port;   // "2266";
            conn.Name             = vault.Name;    //"我的云盘";
            conn.ServerVaultName  = vault.Name;    // "示例库";
            conn.ServerVaultGUID  = vault.Guid;    // "{08ED46E7-C0FF-4D16-BA38-5043144CCD15}";
            conn.UserName         = user.UserName; // "qiuge";
            conn.Password         = user.Password; // "sd2350139";
            conn.Domain           = domain;        // "simuladesign";
            conn.UserSpecific     = true;
            conn.ProtocolSequence = "ncacn_ip_tcp";
            var app           = new MFilesClientApplication();
            var conns         = app.GetVaultConnections();
            var connsSameName = new VaultConnections();

            foreach (VaultConnection co in conns)
            {
                var coGUID = co.ServerVaultGUID;
                if (coGUID == conn.ServerVaultGUID) // && co.Name == conn.Name
                {
                    connsSameName.Add(-1, co);
                }
            }
            if (connsSameName.Count > 0)
            {
                foreach (VaultConnection co in connsSameName)
                {
                    app.RemoveVaultConnection(co.Name, co.UserSpecific);
                }
            }
            app.AddVaultConnection(conn);
            Vault mfVault = null;

            try
            {
                //   Writelog(string.Format(" in getuservault1,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, domain));
                mfVault = LoginVault(conn, user.UserName, user.Password, domain);
            }
            catch
            {
            }
            VaultGuids.Add(vault.Guid);
            return(mfVault);
        }
示例#4
0
        /// <summary>
        /// 获取MFiles中的库
        /// </summary>
        /// <param name="guid">唯一标示</param>
        /// <returns></returns>
        public static Vault GetVaultWithGuid(string guid)
        {
            Vault            vault     = null;
            var              clientApp = new MFilesClientApplication();
            VaultConnections conns     = clientApp.GetVaultConnections();

            foreach (VaultConnection vConn in conns)
            {
                if (vConn.GetGUID() == guid)
                {
                    vault = vConn.BindToVault(IntPtr.Zero, true, true);
                    break;
                }
            }

            return(vault);
        }
示例#5
0
        /// <summary>
        /// 对"参数oVault是否有效"进行核实,若登出,则重连
        /// </summary>
        /// <param name="oVault">MFilesAPI.Vault</param>
        /// <param name="user"></param>
        /// <param name="vaultGuid">客户端库GUID</param>
        public static Vault Connect2Vault(Vault oVault, UserDto user, string vaultGuid)
        {
            //  Writelog(string.Format(" in Connect2Vault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
            Vault vault = oVault;

            if (!oVault.LoggedIn)
            {
                var clientApp          = new MFilesClientApplication();
                VaultConnections conns = clientApp.GetVaultConnections();
                foreach (VaultConnection vConn in conns)
                {
                    if (vConn.GetGUID() == vaultGuid)
                    {
                        vault = LoginVault(vConn, user.UserName, user.Password, user.Domain);
                        break;
                    }
                }
            }
            return(vault);
        }
示例#6
0
        public static void LogoutVault(string vaultGuid)
        {
            var app = new MFilesClientApplication();
            var vcs = app.GetVaultConnectionsWithGUID(vaultGuid);

            foreach (VaultConnection vc in vcs)
            {
                if (vc.IsLoggedIn())
                {
                    var v = vc.BindToVault(IntPtr.Zero, true, true);
                    try
                    {
                        v.LogOutWithDialogs(IntPtr.Zero);
                    }
                    catch
                    {
                    }
                }
            }
        }
示例#7
0
        private void NoticeSet_Load(object sender, EventArgs e)
        {
            treeViewConcern.Nodes.Clear();
            var app = new MFilesClientApplication();
            var vcs = app.GetVaultConnections();
            var all = new TreeNode("全部");

            _scsconf = SeismicControlSettings.Load();
            foreach (VaultConnection vc in vcs)
            {
                var onevault = new TreeNode(vc.Name);

                foreach (var a in _noticetypes)
                {
                    onevault.Nodes.Add(a);
                }
                all.Nodes.Add(onevault);
            }
            treeViewConcern.CheckBoxes = true;
            treeViewConcern.Nodes.Add(all);
            foreach (TreeNode b in treeViewConcern.Nodes)
            {
                b.Expand();
            }

            foreach (TreeNode tn in treeViewConcern.Nodes)
            {
                tn.Checked = true;
                foreach (TreeNode stn in tn.Nodes)
                {
                    stn.Checked = InitFromConf(_scsconf, stn.Text);
                    VaultConfs.Add(new VaultConf {
                        Vaultname = stn.Text, IsConcerned = stn.Checked
                    });
                    foreach (TreeNode sstn in stn.Nodes)
                    {
                        sstn.Checked = InitFromConf(_scsconf, stn.Text, sstn.Text);
                    }
                }
            }
        }
示例#8
0
        public DavisInvoice()
        {
            InitializeComponent();
            //connect to mFiles
            var mFilesApp = new MFilesClientApplication();


            //open vault
            var vaultConnect = new VaultConnection();

            vaultConnect = mFilesApp.GetVaultConnectionsWithGUID("{" + Properties.Settings.Default.vaultGUID + "}").Cast <VaultConnection>().FirstOrDefault();

            var currVault = new Vault();

            currVault = vaultConnect.BindToVault(this.Handle, true, false);

            //export
            button1.Click += delegate(object sender, EventArgs e) { button1_Click(sender, e, currVault, mFilesApp); };
            //import
            button2.Click += delegate(object sender, EventArgs e) { button2_Click(sender, e, currVault, mFilesApp); };
        }
示例#9
0
        /// <summary>
        /// 连接MFiles库
        /// </summary>
        /// <returns>MFiles 对象Vault</returns>
        public static Vault GetVault(UserDto user, string vaultGuid, bool login = true)
        {
            //string vaultName = "设计云";
            Vault            vault     = null;
            var              clientApp = new MFilesClientApplication();
            VaultConnections conns     = clientApp.GetVaultConnections();
            string           domain    = user.Domain;

            //     Writelog(string.Format(" in GetVault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
            foreach (VaultConnection vConn in conns)
            {
                if (vConn.GetGUID() == vaultGuid)
                {
                    var loggedIn = vConn.IsLoggedIn();
                    if (!loggedIn && !login)
                    {
                        return(null);
                    }
                    if (vConn.IsLoggedIn())
                    {
                        vault = vConn.BindToVault(IntPtr.Zero, true, true);
                        string account = (domain == "" ? user.UserName : domain + "\\" + user.UserName);
                        if (vault.SessionInfo.AccountName != account)
                        {
                            vault.LogOutWithDialogs(IntPtr.Zero);
                            vault = LoginVault(vConn, user.UserName, user.Password, domain);
                        }
                    }
                    else
                    {
                        vault = LoginVault(vConn, user.UserName, user.Password, domain);
                    }
                    break;
                }
            }
            return(vault);
        }
示例#10
0
文件: Form1.cs 项目: IanPId/Docsmart
        public bool ObjectExists(int id)
        {
            var vaultGuid = ((VaultComboBoxItem)vaultComboBox.SelectedItem).VaultGUID;//"{C840BE1A-5B47-4AC0-8EF7-835C166C8E24}";

            // Connect to the vault using a client connection.
            // ref: http://developer.m-files.com/APIs/COM-API/#api-modes-client-vs-server
            // Note: this code will just return the first connection to the vault.
            var clientApplication = new MFilesClientApplication();
            var vault             =
                clientApplication
                .GetVaultConnectionsWithGUID(vaultGuid)
                .Cast <VaultConnection>()
                .FirstOrDefault()?
                .BindToVault(IntPtr.Zero, true, true);

            if (null == vault)
            {
                throw new NotImplementedException("Vault connection not found");
            }
            var objectSearch = new MFSearchBuilder(vault);

            objectSearch.Deleted(false);
            objectSearch.ObjType(MFBuiltInObjectType.MFBuiltInObjectTypeDocument);
            objectSearch.Class((int)vault.ClassOperations.GetObjectClassIDByAlias("Class.FerretArchiveDocument"));
            objectSearch.Conditions.AddPropertyCondition(
                (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.FerretDocId"),
                MFConditionType.MFConditionTypeEqual,
                MFDataType.MFDatatypeInteger,
                id);
            var objectResults = objectSearch.Find();

            if (objectResults.Count >= 1)
            {
                return(true);
            }
            return(false);
        }
示例#11
0
 public static MFilesClientApplication GetClientApp()
 {
     return(_app ?? (_app = new MFilesClientApplication()));
 }
示例#12
0
        //Export Button
        private void button1_Click(object sender, EventArgs e, Vault currVault, MFilesClientApplication mFilesApp)
        {
            //MessageBox.Show(currVault.Name);

            SaveFileDialog saveFile = new SaveFileDialog();

            saveFile.Filter = "XML Files (*.xml)|*.xml";


            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                //pull invoices using search conditions
                var searchConditions = new SearchConditions();

                //is it not deleted
                var isNotDeleted = new SearchCondition();
                isNotDeleted.Expression.DataStatusValueType         = MFStatusType.MFStatusTypeDeleted;
                isNotDeleted.Expression.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp;
                isNotDeleted.ConditionType = MFConditionType.MFConditionTypeNotEqual;
                isNotDeleted.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, true);
                searchConditions.Add(-1, isNotDeleted);

                //is it part of the Invoice workflow
                var isInvoice = new SearchCondition();
                isInvoice.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefWorkflow;
                isInvoice.ConditionType = MFConditionType.MFConditionTypeEqual;
                isInvoice.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.invoiceWorkflow);
                searchConditions.Add(-1, isInvoice);

                //is it in the accounting state
                var isAccounting = new SearchCondition();
                isAccounting.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState;
                isAccounting.ConditionType = MFConditionType.MFConditionTypeEqual;
                isAccounting.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateAccounting);
                searchConditions.Add(-1, isAccounting);

                //Perform search
                var invoices = currVault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions, MFSearchFlags.MFSearchFlagNone, false);


                //start output file
                XElement output   = new XElement("YsiTran");
                XElement payables = new XElement("Payables");

                //get post month
                var postMonthForm = new PostMonth();
                postMonthForm.ShowDialog();

                //loop through invoices collecting at import workflow state, build XML file from the inside out.
                int count = 0;
                foreach (ObjectVersion invoice in invoices)
                {
                    XElement payable     = new XElement("Payable");
                    double   totalAmount = 0;
                    count++;

                    var propValues        = new PropertyValues();
                    var currPropertyValue = new PropertyValue();
                    var objLedger         = new ObjectVersion();
                    propValues = currVault.ObjectPropertyOperations.GetProperties(invoice.ObjVer);

                    XElement details = new XElement("Details");

                    //Get Ledger Entry reference
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propLedgerEntry);

                    if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup)
                    {
                        var lookups = new Lookups();

                        lookups = currPropertyValue.TypedValue.GetValueAsLookups();

                        int i = 0;
                        foreach (Lookup lookup in lookups)
                        {
                            XElement detail = new XElement("Detail");

                            var propDef = new PropertyDef();
                            propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef);
                            var valListObjType = new ObjType();
                            valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList);

                            if (valListObjType.RealObjectType)
                            {
                                i++;
                                //Get Ledgery Entry Object
                                var objDetail = new ObjVer();
                                objDetail.SetIDs(valListObjType.ID, lookup.Item, lookup.Version);
                                var detailValues = new PropertyValues();
                                var detailValue  = new PropertyValue();
                                detailValues = currVault.ObjectPropertyOperations.GetProperties(objDetail);
                                //MessageBox.Show(i.ToString());
                                //Get Account
                                detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propAccount);
                                if (detailValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup)
                                {
                                    Lookup lookupAccount = new Lookup();
                                    lookupAccount = detailValue.TypedValue.GetValueAsLookup();

                                    propDef        = currVault.PropertyDefOperations.GetPropertyDef(detailValue.PropertyDef);
                                    valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList);

                                    if (valListObjType.RealObjectType)
                                    {
                                        //Get Account Number
                                        var objAccount = new ObjVer();
                                        objAccount.SetIDs(valListObjType.ID, lookupAccount.Item, lookupAccount.Version);
                                        var accountValues = new PropertyValues();
                                        var accountValue  = new PropertyValue();
                                        accountValues = currVault.ObjectPropertyOperations.GetProperties(objAccount);
                                        accountValue  = accountValues.SearchForProperty(Properties.Settings.Default.propGLCode);
                                        XElement account = new XElement("AccountId");
                                        account.SetValue(accountValue.GetValueAsLocalizedText());
                                        detail.Add(account);
                                    }
                                }

                                //get Description-Notes
                                detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propDescription);
                                XElement notes = new XElement("Notes");
                                notes.SetValue(detailValue.GetValueAsLocalizedText());
                                detail.Add(notes);

                                //get Amount
                                detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propGLAmount);
                                XElement amount = new XElement("Amount");
                                amount.SetValue(detailValue.GetValueAsLocalizedText());
                                detail.Add(amount);
                                totalAmount += Convert.ToDouble(detailValue.GetValueAsLocalizedText());
                            }

                            XElement propertyID = new XElement("PropertyId");
                            detail.Add(propertyID);
                            details.Add(detail);
                        }
                    }

                    //Get Property ID
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propProperty);
                    if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup)
                    {
                        //Getlookup of property to find object
                        var lookup = new Lookup();
                        lookup = currPropertyValue.TypedValue.GetValueAsLookup();
                        var propDef = new PropertyDef();
                        propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef);
                        var valListObjType = new ObjType();
                        valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList);

                        if (valListObjType.RealObjectType)
                        {
                            //Get property ID
                            var objProperty = new ObjVer();
                            objProperty.SetIDs(valListObjType.ID, lookup.Item, lookup.Version);
                            var propertyValues = new PropertyValues();
                            var propertyValue  = new PropertyValue();
                            propertyValues = currVault.ObjectPropertyOperations.GetProperties(objProperty);
                            propertyValue  = propertyValues.SearchForProperty(Properties.Settings.Default.propPropertyID);



                            IEnumerable <XElement> ieDetails = from el in details.Elements() select el;


                            //loop through items

                            foreach (XElement detail in ieDetails)
                            {
                                //Check that a check has been cut in Yardi.
                                if (detail.Elements("PropertyId").Any())
                                {
                                    detail.Element("PropertyId").SetValue(propertyValue.GetValueAsLocalizedText());
                                }
                            }
                        }
                    }

                    //Get Vendor ID
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propVendor);
                    if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup)
                    {
                        //Getlookup of vendor to find object
                        var lookup = new Lookup();
                        lookup = currPropertyValue.TypedValue.GetValueAsLookup();
                        var propDef = new PropertyDef();
                        propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef);
                        var valListObjType = new ObjType();
                        valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList);

                        if (valListObjType.RealObjectType)
                        {
                            //Get Vendor ID
                            var objProperty = new ObjVer();
                            objProperty.SetIDs(valListObjType.ID, lookup.Item, lookup.Version);
                            var vendorValues = new PropertyValues();
                            var vendorValue  = new PropertyValue();
                            vendorValues = currVault.ObjectPropertyOperations.GetProperties(objProperty);
                            vendorValue  = vendorValues.SearchForProperty(Properties.Settings.Default.propYardiCode);
                            XElement propertyID = new XElement("PersonId");
                            propertyID.SetValue(vendorValue.GetValueAsLocalizedText());
                            payable.Add(propertyID);
                        }
                    }

                    // Add details to payable
                    payable.Add(details);

                    //Add Post Month
                    XElement postMonth = new XElement("PostMonth");
                    postMonth.SetValue(postMonthForm.StrPostMonth);
                    payable.Add(postMonth);

                    //Get link to object
                    XElement link    = new XElement("Notes");
                    string   strLink = "m-files://show/" + Properties.Settings.Default.vaultGUID + "/" + invoice.ObjVer.Type.ToString() + "-" + invoice.ObjVer.ID.ToString();
                    link.SetValue(strLink);
                    payable.Add(link);

                    //get Invoice Number
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propInvoiceNumber);
                    XElement invoiceNumber = new XElement("InvoiceNumber");
                    invoiceNumber.SetValue(currPropertyValue.GetValueAsLocalizedText());
                    payable.Add(invoiceNumber);

                    //get Invoice date
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propInvoiceDate);
                    XElement invoiceDate = new XElement("InvoiceDate");
                    invoiceDate.SetValue(currPropertyValue.GetValueAsLocalizedText());
                    payable.Add(invoiceDate);

                    //get Due Date
                    currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propDueDate);
                    XElement dueDate = new XElement("DueDate");
                    dueDate.SetValue(currPropertyValue.GetValueAsLocalizedText());
                    payable.Add(dueDate);

                    //Set Expense Type
                    XElement expenseType = new XElement("ExpenseType");
                    expenseType.SetValue("Contract");
                    payable.Add(expenseType);


                    //Set Total
                    XElement total = new XElement("TotalAmount");
                    total.SetValue(totalAmount.ToString());


                    payables.Add(payable);

                    //change workflow state
                    propValues.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState).TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateProcessing);
                    currVault.ObjectPropertyOperations.SetAllProperties(invoice.ObjVer, true, propValues);
                }



                output.Add(payables);
                output.Save(saveFile.FileName);
                MessageBox.Show(count.ToString() + " Files Exported!");
            }
        }
示例#13
0
        private void button2_Click(object sender, EventArgs e, Vault currVault, MFilesClientApplication mFilesApp)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.Filter = "XML Files (*.xml) | *.xml";

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                //open XML file
                XElement inputFile = XElement.Load(openFile.FileName);
                IEnumerable <XElement> inputxml = from el in inputFile.Element("Payables").Elements() select el;


                //loop through items
                int count = 0;
                foreach (XElement payable in inputxml)
                {
                    //Check that a check has been cut in Yardi.
                    if (payable.Element("Details").Element("Detail").Elements("CheckNumber").Any())
                    {
                        string checkNumber = payable.Element("Details").Element("Detail").Element("CheckNumber").Value;
                        //MessageBox.Show(checkNumber);

                        //Find Invoice in mFiles
                        //pull invoices using search conditions
                        var searchConditions = new SearchConditions();

                        //is it not deleted
                        var isNotDeleted = new SearchCondition();
                        isNotDeleted.Expression.DataStatusValueType         = MFStatusType.MFStatusTypeDeleted;
                        isNotDeleted.Expression.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp;
                        isNotDeleted.ConditionType = MFConditionType.MFConditionTypeNotEqual;
                        isNotDeleted.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, true);
                        searchConditions.Add(-1, isNotDeleted);

                        //is it part of the Invoice workflow
                        var isInvoice = new SearchCondition();
                        isInvoice.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefWorkflow;
                        isInvoice.ConditionType = MFConditionType.MFConditionTypeEqual;
                        isInvoice.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.invoiceWorkflow);
                        searchConditions.Add(-1, isInvoice);

                        //is it in the payment processing state
                        var isAccounting = new SearchCondition();
                        isAccounting.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState;
                        isAccounting.ConditionType = MFConditionType.MFConditionTypeEqual;
                        isAccounting.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateProcessing);
                        searchConditions.Add(-1, isAccounting);

                        //is it the correct payable
                        var isPayable = new SearchCondition();
                        isPayable.Expression.DataPropertyValuePropertyDef = Properties.Settings.Default.propInvoiceNumber;
                        isPayable.ConditionType = MFConditionType.MFConditionTypeEqual;
                        isPayable.TypedValue.SetValue(MFDataType.MFDatatypeText, payable.Element("InvoiceNumber").Value);
                        searchConditions.Add(-1, isPayable);

                        //Perform search
                        var invoices = currVault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions, MFSearchFlags.MFSearchFlagNone, false);

                        foreach (ObjectVersion invoice in invoices)
                        {
                            var propValues        = new PropertyValues();
                            var currPropertyValue = new PropertyValue();
                            propValues = currVault.ObjectPropertyOperations.GetProperties(invoice.ObjVer);

                            //currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propCheckNumber);
                            count++;
                            propValues.SearchForProperty(Properties.Settings.Default.propCheckNumber).TypedValue.SetValue(MFDataType.MFDatatypeText, checkNumber);
                            //change workflow state
                            propValues.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState).TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateComplete);
                            currVault.ObjectPropertyOperations.SetAllProperties(invoice.ObjVer, true, propValues);
                        }
                    }
                }
                MessageBox.Show(count.ToString() + " Invoices update in mFiles!");
            }
        }
 public MainForm()
 {
     InitializeComponent();
     clientApp = new MFilesClientApplication();
 }
示例#15
0
        public static VaultConnection InitialVaultConnection(UserDto user, VaultDto vault)
        {
            var app   = new MFilesClientApplication();
            var conns = app.GetVaultConnectionsWithGUID(vault.Guid);
            //var count = conns.Count;
            var             removeConns = new List <VaultConnection>();
            VaultConnection connection  = null;

            foreach (VaultConnection vc in conns)
            {
                if (vc.NetworkAddress != vault.Server.Ip ||
                    vc.Name != vault.Name ||
                    vc.Endpoint != vault.Server.Port)
                {
                    removeConns.Add(vc);
                }
                else
                {
                    connection = vc;
                }
            }
            if (removeConns.Count > 0)
            {
                foreach (var vc in removeConns)
                {
                    app.RemoveVaultConnection(vc.Name, vc.UserSpecific);
                }
            }
            if (connection == null)
            {
                connection = new VaultConnection
                {
                    AuthType         = MFAuthType.MFAuthTypeSpecificWindowsUser,
                    AutoLogin        = false,
                    NetworkAddress   = vault.Server.Ip,
                    Endpoint         = vault.Server.Port,
                    Name             = vault.Name,
                    ServerVaultName  = vault.Name,
                    ServerVaultGUID  = vault.Guid,
                    UserName         = user.UserName,
                    Password         = user.Password,
                    Domain           = user.Domain,
                    UserSpecific     = true,
                    ProtocolSequence = "ncacn_ip_tcp"
                };
                app.AddVaultConnection(connection);
            }
            //var now = DateTime.Now;
            Vault mfVault = null;

            if (connection.IsLoggedIn())
            {
                var v = connection.BindToVault(IntPtr.Zero, true, true);
                if (v != null)
                {
                    var accountName = v.SessionInfo.AccountName;
                    var index       = accountName.IndexOf('\\');
                    var userName    = accountName.Substring(index + 1);
                    if (StringComparer.OrdinalIgnoreCase.Equals(userName, user.UserName))
                    {
                        mfVault = v;
                    }
                    else
                    {
                        v.LogOutWithDialogs(IntPtr.Zero);
                    }
                }
            }
            return(connection);
        }
示例#16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <param name="vault"></param>
        /// <param name="forceLogout">是否强制退出</param>
        /// <param name="vaultName">库名称</param>
        /// <returns></returns>
        public static Vault GetUserVault(UserDto user, VaultDto vault, bool forceLogout, string vaultName)
        {
            log.Info(" GetUserVault username="******",vault=" + vault.Name);
            if (VaultGuids.Contains(vault.Guid))
            {
                return(GetVault(user, vault.Guid));
            }
            vaultName = vaultName ?? vault.Name;
            var app         = new MFilesClientApplication();
            var removeConns = new List <VaultConnection>();

            try
            {
                var sameVC = app.GetVaultConnection(vault.Name);
                var needR  = Need2Remove(vault, sameVC, vaultName);
                if (needR)
                {
                    removeConns.Add(sameVC);
                }
            }
            catch (Exception ex)
            {
                log.Info(string.Format("GetUserVault error:{0},{1}", vaultName, ex.Message));
            }
            var conns = app.GetVaultConnectionsWithGUID(vault.Guid);

            VaultConnection connection = null;

            foreach (VaultConnection vc in conns)
            {
                var needR = Need2Remove(vault, vc, vaultName);
                if (needR)
                {
                    removeConns.Add(vc);
                }
                else
                {
                    connection = vc;
                }
            }
            if (removeConns.Count > 0)
            {
                foreach (var vc in removeConns)
                {
                    app.RemoveVaultConnection(vc.Name, vc.UserSpecific);
                }
            }
            if (connection == null)
            {
                connection = new VaultConnection
                {
                    AuthType         = MFAuthType.MFAuthTypeSpecificWindowsUser,
                    AutoLogin        = false,
                    NetworkAddress   = vault.Server.Ip,
                    Endpoint         = vault.Server.Port,
                    Name             = vaultName,
                    ServerVaultName  = vault.Name,
                    ServerVaultGUID  = vault.Guid,
                    UserName         = user.UserName,
                    Password         = user.Password,
                    Domain           = user.Domain,
                    UserSpecific     = true,
                    ProtocolSequence = "ncacn_ip_tcp"
                };
                if (String.IsNullOrEmpty(user.Domain))
                {
                    connection.AuthType = MFAuthType.MFAuthTypeSpecificMFilesUser;
                }
                app.AddVaultConnection(connection);
            }
            //var now = DateTime.Now;
            Vault mfVault = null;

            if (connection.IsLoggedIn())
            {
                var v = connection.BindToVault(IntPtr.Zero, true, true);
                if (v != null)
                {
                    if (forceLogout)
                    {
                        try
                        {
                            v.LogOutWithDialogs(IntPtr.Zero);
                        }
                        catch
                        {
                            log.Info("Remote Loggin time11111: " + DateTime.Now);
                        }
                    }
                    else
                    {
                        var accountName = v.SessionInfo.AccountName;
                        var index       = accountName.IndexOf('\\');
                        var userName    = accountName.Substring(index + 1);
                        if (StringComparer.OrdinalIgnoreCase.Equals(userName, user.UserName))
                        {
                            mfVault = v;
                        }
                        else
                        {
                            try
                            {
                                v.LogOutWithDialogs(IntPtr.Zero);
                            }
                            catch
                            {
                                log.Info("Remote Loggin time 22222: " + DateTime.Now);
                            }
                        }
                    }
                }
            }
            log.Info("Remote Loggin time: " + DateTime.Now);

            try
            {
                //now = DateTime.Now;
                var has = false;
                log.Info(string.Format(" in getuservault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
                if (forceLogout)
                {
                    mfVault = LoginVault(connection, user.UserName, user.Password, user.Domain);
                    has     = true;
                }
                if (mfVault == null || !has)
                {
                    mfVault = LoginVault(connection, user.UserName, user.Password, user.Domain);
                }
                log.Info("Loggin time: " + DateTime.Now);
            }
            catch
            {
                log.Info("Remote Loggin time: 33333" + DateTime.Now);
            }
            VaultGuids.Add(vault.Guid);
            return(mfVault);
        }
示例#17
0
文件: Form1.cs 项目: IanPId/Docsmart
        private void LoadToMfiles(string nameOrTitle, string documentDate, string ferretDocumentClass, string accountNumber, string clientName, string description, string extension, int docID, string filepath)
        {
            #region
            // Which vault are we connecting to?
            var vaultGuid = ((VaultComboBoxItem)vaultComboBox.SelectedItem).VaultGUID;//"{C840BE1A-5B47-4AC0-8EF7-835C166C8E24}";

            // Connect to the vault using a client connection.
            // ref: http://developer.m-files.com/APIs/COM-API/#api-modes-client-vs-server
            // Note: this code will just return the first connection to the vault.
            var clientApplication = new MFilesClientApplication();
            var vault             =
                clientApplication
                .GetVaultConnectionsWithGUID(vaultGuid)
                .Cast <VaultConnection>()
                .FirstOrDefault()?
                .BindToVault(IntPtr.Zero, true, true);
            if (null == vault)
            {
                throw new NotImplementedException("Vault connection not found");
            }

            long length = new System.IO.FileInfo("C:\\temp\\New_Sample.txt").Length;

            // Define the property values for the new object.
            var propertyValues = new MFilesAPI.PropertyValues();

            // Class.
            var classPropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass
            };
            classPropertyValue.Value.SetValue(
                MFDataType.MFDatatypeLookup,  // This must be correct for the property definition.
                                              //(int)MFBuiltInDocumentClass.MFBuiltInDocumentClassOtherDocument
                (int)vault.ClassOperations.GetObjectClassIDByAlias("Class.FerretArchiveDocument")
                );
            propertyValues.Add(-1, classPropertyValue);

            // Name or title.
            var nameOrTitlePropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle
            };
            nameOrTitlePropertyValue.Value.SetValue(
                MFDataType.MFDatatypeText,  // This must be correct for the property definition.
                nameOrTitle
                );
            propertyValues.Add(-1, nameOrTitlePropertyValue);

            //Douument Date
            var docDatePropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.DocumentDate")
            };
            docDatePropertyValue.Value.SetValue(
                MFDataType.MFDatatypeDate,
                documentDate
                );
            propertyValues.Add(-1, docDatePropertyValue);

            // Ferret Document Class
            var ferretDocumentClassPropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.FerretDocumentClass")
            };
            ferretDocumentClassPropertyValue.Value.SetValue(
                MFDataType.MFDatatypeText,
                ferretDocumentClass
                );
            propertyValues.Add(-1, ferretDocumentClassPropertyValue);

            // Account Number
            var accountNumberPropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.AccountNumber")
            };
            accountNumberPropertyValue.Value.SetValue(
                MFDataType.MFDatatypeText,
                accountNumber
                );
            propertyValues.Add(-1, accountNumberPropertyValue);

            // Client Name
            var clientNamePropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.ClientName")
            };
            clientNamePropertyValue.Value.SetValue(
                MFDataType.MFDatatypeText,
                clientName
                );
            propertyValues.Add(-1, clientNamePropertyValue);

            // Description
            var descriptionPropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.Description")
            };
            descriptionPropertyValue.Value.SetValue(
                MFDataType.MFDatatypeText,
                description
                );
            propertyValues.Add(-1, descriptionPropertyValue);

            //Ferret Doc Id
            var docIdPropertyValue = new MFilesAPI.PropertyValue()
            {
                PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.FerretDocId")
            };
            docIdPropertyValue.Value.SetValue(
                MFDataType.MFDatatypeInteger,
                docID
                );
            propertyValues.Add(-1, docIdPropertyValue);

            // Define the source files to add.
            var sourceFiles = new MFilesAPI.SourceObjectFiles();

            // Add one file.
            var myFile = new MFilesAPI.SourceObjectFile();
            myFile.SourceFilePath = @"C:\temp\\New_Sample.txt";
            myFile.Title          = "My test document"; // For single-file-documents this is ignored.
            myFile.Extension      = extension.Replace(".", "");
            sourceFiles.Add(-1, myFile);

            // What object type is being created?
            var objectTypeID = (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument;

            // A "single file document" must be both a document and contain exactly one file.
            var isSingleFileDocument =
                objectTypeID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument && sourceFiles.Count == 1;
            #endregion
            // Create the object and check it in.
            try
            {
                if (length != 0)
                {
                    var objectVersion = vault.ObjectOperations.CreateNewObjectEx(
                        objectTypeID,
                        propertyValues,
                        sourceFiles,
                        SFD: isSingleFileDocument,
                        CheckIn: true);
                    string msg = string.Format("Record {0}", docID);
                    WriteLog("Success:", msg);
                }
                else
                {
                    // Define the source files to add.
                    //var sourceFiles1 = new MFilesAPI.SourceObjectFiles();

                    //// Add one file.
                    //var myFile1 = new MFilesAPI.SourceObjectFile();
                    //myFile1.SourceFilePath = filepath;
                    //myFile1.Title = "My test document"; // For single-file-documents this is ignored.
                    //myFile1.Extension = extension.Replace(".", "");
                    //sourceFiles1.Add(-1, myFile1);

                    //var objectVersion = vault.ObjectOperations.CreateNewObjectEx(
                    //    objectTypeID,
                    //    propertyValues,
                    //    sourceFiles1,
                    //    SFD: isSingleFileDocument,
                    //    CheckIn: true);
                    //string msg = string.Format("Record {0}", docID);
                    //WriteLog("Success:", msg);
                    string ErrorMsg = string.Format("Record {0}, Document Name {1} dated {2} for account {3}. Msg is {4} ", docID, nameOrTitle, documentDate, accountNumber, "File size 0"); // e.Message);
                    WriteLog("Error:", ErrorMsg);
                    // string loadLog = string.Format("{0},(1},{2},{3},{4},{5},{6}", nameOrTitle, documentDate, ferretDocumentClass, accountNumber, clientName, description, filepath);
                    //  WriteErrorLog(loadLog);
                }
            }
            catch (System.IO.IOException e)
            {
                //try
                //{
                //    // Define the source files to add.
                //    var sourceFiles1 = new MFilesAPI.SourceObjectFiles();

                //    // Add one file.
                //    var myFile1 = new MFilesAPI.SourceObjectFile();
                //    myFile1.SourceFilePath = filepath;
                //    myFile1.Title = "My test document"; // For single-file-documents this is ignored.
                //    myFile1.Extension = extension.Replace(".", "");
                //    sourceFiles1.Add(-1, myFile1);

                //    var objectVersion = vault.ObjectOperations.CreateNewObjectEx(
                //        objectTypeID,
                //        propertyValues,
                //        sourceFiles1,
                //        SFD: isSingleFileDocument,
                //        CheckIn: true);
                //    string msg = string.Format("Record {0}", docID);
                //    WriteLog("Success:", msg);
                //}
                //catch
                {
                    string ErrorMsg = string.Format("Record {0}, Document Name {1} dated {2} for account {3}. Msg is {4} ", docID, nameOrTitle, documentDate, accountNumber, e.Message);
                    WriteLog("Error:", ErrorMsg);
                    string loadLog = string.Format("{0},(1},{2},{3},{4},{5},{6}", nameOrTitle, documentDate, ferretDocumentClass, accountNumber, clientName, description, filepath);
                    WriteErrorLog(loadLog);
                }
            }
        }
示例#18
0
        public void Launch(string applicationPath, dynamic dynVault, dynamic dynListItems)
        {
            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }

            // TODO: heard this is bad, but don't have another way to do it currently
            // Need to set the app path because it is used later on to get the bin
            //AppDomain.CurrentDomain.SetData( "APPBASE", Path.Combine( applicationPath, "bin" ) );
            // Sets AppDomain.CurrentDomain.BaseDirectory
            AppDomain.CurrentDomain.SetData("APPBASE", applicationPath);

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            Console.WriteLine("Launching");

            this._console = new BufferedConsole();

            try
            {
                var config     = Config.Create(ScriptCsArgs.Parse(new string[] { }));
                var scriptArgs = new string[] { };
                config.Console = this._console;
                var scriptServicesBuilder = (ScriptServicesBuilder)ScriptServicesBuilderFactory.Create(config, scriptArgs);

                var clientApp       = new MFilesClientApplication();
                var clientVault     = clientApp.BindToVault((string)dynVault.Name, IntPtr.Zero, true, true);
                var props           = clientVault.PropertyDefOperations.GetPropertyDefs();
                var propsDictionary = new Dictionary <string, MFIdentifier>();
                foreach (PropertyDef propertyDef in props)
                {
                    // TODO: what if multiple have same name?
                    propsDictionary.Add(propertyDef.Name, new MFIdentifier(propertyDef.GUID));
                }
                var globs = new ScriptHostArguments
                {
                    Vault = clientVault,
                    // TODO: convert this list using clientVault to something useful
                    // TODO: move the script dashboard to non popup (that way we can pass the current listing)? what if there are multiple? (home page)
                    ListingItems = dynListItems,
                    Properties   = propsDictionary
                };
                var myFactory = new MFilesScriptHostFactory(globs, this._console);
                scriptServicesBuilder.SetOverride <IScriptHostFactory, MFilesScriptHostFactory>(myFactory);
                scriptServicesBuilder.SetOverride <IRepl, MFilesRepl>();
                var scriptServices = scriptServicesBuilder.Build();

                var runtimeServices = (RuntimeServices)scriptServicesBuilder.RuntimeServices;
                runtimeServices.Container.Resolve <Printers>().AddCustomPrinter <Vault>(vault => vault.Name);
                runtimeServices.Container.Resolve <Printers>().AddCustomPrinter <IVault>(vault => vault.Name);
                runtimeServices.Container.Resolve <Printers>().AddCustomPrinter <VaultClass>(vault => vault.Name);
                runtimeServices.Container.Resolve <Printers>().AddCustomPrinter <MFSearchBuilder>(search => $"Search for {search.Vault.Name} ({search.Conditions.Count})");

                this._command = new HtmlExecuteReplCommand(config.ScriptName, scriptArgs, scriptServices);
                this._command.Repl.Initialize();
                this._command.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to set up script services");
                Console.WriteLine(e);
            }
        }