private async Task <bool> CreatFileInMFileAsync(string productTitle, string productId, string serial)
        {
            // Which file do we need to upload?
            string path = AppDomain.CurrentDomain.BaseDirectory + "Assets\\uploads\\test.pdf";
            var    localFileToUpload = new System.IO.FileInfo(path);

            var uploadFileResponse = await client.PostAsync(new Uri(userinfo.BaseUrl + "REST/files.aspx"),
                                                            new System.Net.Http.StreamContent(localFileToUpload.OpenRead()));

            // Extract the value.
            var uploadInfo = JsonConvert.DeserializeObject <UploadInfo>(
                await uploadFileResponse.Content.ReadAsStringAsync());

            // Ensure the extension is set.
            // NOTE: This must be without the dot!
            uploadInfo.Extension = localFileToUpload.Extension.Substring(1);
            try
            {
                // Add the upload to the objectCreationInfo.
                var objectCreationInfo = new ObjectCreationInfo()
                {
                    PropertyValues = new[]
                    {
                        new PropertyValue()
                        {
                            PropertyDef = 100, // The built-in "Class" property Id.
                            TypedValue  = new TypedValue()
                            {
                                DataType = MFDataType.Lookup,
                                Lookup   = new Lookup()
                                {
                                    Item    = userinfo.MQCReportId, // The built-in "QC Report" class Id.
                                    Version = -1                    // Work around the bug detailed below.
                                }
                            }
                        },
                        new PropertyValue()
                        {
                            PropertyDef = userinfo.MProductPropertyId, // The built-in "Class" property Id.
                            TypedValue  = new TypedValue()
                            {
                                DataType = MFDataType.MultiSelectLookup,
                                Lookups  = new List <Lookup>()
                                {
                                    new Lookup()
                                    {
                                        Item         = int.Parse(productId),
                                        Version      = -1,
                                        DisplayValue = productTitle
                                    }
                                }
                            }
                        },
                        new PropertyValue()
                        {
                            PropertyDef = 0, // The built-in "Name or Title" property Id.
                            TypedValue  = new TypedValue()
                            {
                                DataType = MFDataType.Text,
                                Value    = serial // here the pdf file title decide
                            }
                        },
                        new PropertyValue()
                        {
                            PropertyDef = userinfo.MSerialId, // The Serial property Id.
                            TypedValue  = new TypedValue()
                            {
                                DataType = MFDataType.Text,
                                Value    = serial // here the serial of pdf file is decided as you want.
                            }
                        }
                    }
                };

                objectCreationInfo.Files = new UploadInfo[]
                {
                    uploadInfo
                };
                // Serialise using JSON.NET (use Nuget to add a reference if needed).
                var stringContent = JsonConvert.SerializeObject(objectCreationInfo);

                // Create the content for the web request.
                var content = new System.Net.Http.StringContent(stringContent, Encoding.UTF8, "application/json");

                // We are creating a document
                const int documentObjectTypeId = 0; //

                // Execute the POST.
                var httpResponseMessage = await client.PostAsync(new Uri(userinfo.BaseUrl + "REST/objects/" + documentObjectTypeId + ".aspx"), content);

                // Extract the value.
                var objectVersion = JsonConvert.DeserializeObject <ObjectVersion>(
                    await httpResponseMessage.Content.ReadAsStringAsync());

                int fileId = objectVersion.ObjVer.ID;
            }
            catch
            {
                return(false);
            }
            return(true);
        }
示例#2
0
        public ObjectWindowResult ShowPrefilledNewObjectWindow(IntPtr parentWindow, MFObjectWindowMode mode, ObjectCreationInfo objectCreationInfo, PropertyValues prefilledPropertyValues = null, AccessControlList accessControlList = null)
        {
            vault.MetricGatherer.MethodCalled();

            throw new NotImplementedException();
        }
        static void Main(string[] args)
        {
            //Auth object
            var auth = new Authentication
            {
                Username    = Constants.UserName,
                Password    = Constants.Password,
                WindowsUser = false,              // Change to 'true' if using Windows-credentials.
                VaultGuid   = Constants.VaultGUID // Use GUID format with {braces}.
            };

            //External ID Set Path
            var extensionMethodPath = $"{Constants.RestURL}/REST/vault/extensionmethod/SetExternalId";

            #region Authenticate
            // Create the web request.
            var request = CreateRequest($"{Constants.RestURL}/REST/server/authenticationtokens.aspx", "POST", auth);

            // Get the response.
            var response = (HttpWebResponse)request.GetResponse();

            // Deserialize the authentication token.
            var deserializer = new DataContractJsonSerializer(typeof(PrimitiveType <string>));
            var token        = (PrimitiveType <string>)deserializer.ReadObject(response.GetResponseStream());
            #endregion

            #region Get All Employees
            var getAllEmployeePath = $"{Constants.RestURL}/REST/Objects/{Constants.EmployeeObjectId}";

            request = CreateRequest(getAllEmployeePath, "GET");
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(Results <ObjectVersion>));

            var result = (Results <ObjectVersion>)deserializer.ReadObject(response.GetResponseStream());
            #endregion

            #region Create Employee

            var extSystemEmployeeId = Guid.NewGuid().ToString("N");

            //Create employee
            var creationInfo = new ObjectCreationInfo
            {
                PropertyValues = new PropertyValue[] {
                    //Employee class
                    new PropertyValue {
                        PropertyDef = 100, //Built-in class ID not parametrical
                        TypedValue  = new TypedValue {
                            DataType = MFDataType.Lookup, HasValue = true, Lookup = new Lookup {
                                Version = -1, Item = Constants.EmployeeClassId
                            }
                        }
                    },

                    //Name
                    new PropertyValue {
                        PropertyDef = Constants.NameSurnamePropId,
                        TypedValue  = new TypedValue {
                            DataType = MFDataType.Text, Value = "Gökay Kıvırcıoğlu"
                        }
                    },

                    //Working status
                    new PropertyValue {
                        PropertyDef = Constants.WorkingStatusPropId,
                        TypedValue  = new TypedValue {
                            DataType = MFDataType.Lookup, Lookup = new Lookup {
                                Item = Constants.WorkingStatusActiveId, Version = -1
                            }
                        }
                    },
                },

                Files = new UploadInfo[] { }
            };



            var createPath = $"{Constants.RestURL}/REST/Objects/{Constants.EmployeeObjectId}";


            //Create Employee Object
            request = CreateRequest(createPath, "POST", creationInfo);
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ObjectVersion));

            var employeeResult = (ObjectVersion)deserializer.ReadObject(response.GetResponseStream());

            #endregion

            #region Set Employee ExternalId
            var extIdData = new RequestData {
                InternalId = employeeResult.ObjVer.ID.ToString(), ObjectTypeId = Constants.EmployeeObjectId.ToString(), ExternalId = extSystemEmployeeId
            };

            request = CreateRequest(extensionMethodPath, "POST", extIdData);
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ResponseMessage));

            var extensionMethodResult = (ResponseMessage)deserializer.ReadObject(response.GetResponseStream());
            #endregion

            #region Update Employee
            var checkOutPath = $"{Constants.RestURL}/REST/objects/{Constants.EmployeeObjectId}/{employeeResult.ObjVer.ID}/latest/checkedout.aspx?_method=PUT";

            var checkOutType = new PrimitiveType <MFCheckOutStatus>();
            checkOutType.Value = MFCheckOutStatus.CheckedOut;

            request = CreateRequest(checkOutPath, "POST", checkOutType);
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ObjectVersion));

            var checkedOutEmployee = (ObjectVersion)deserializer.ReadObject(response.GetResponseStream());

            var updatePropertyPath = $"{Constants.RestURL}/REST/objects/{Constants.EmployeeObjectId}/{checkedOutEmployee.ObjVer.ID}/latest/properties";

            //Add a new field to employee object
            var tcknProp = new PropertyValue
            {
                PropertyDef = Constants.TCKNPropId,
                TypedValue  = new TypedValue {
                    DataType = MFDataType.Text, Value = "32472832270"
                }
            };

            var nameProp = new PropertyValue
            {
                PropertyDef = Constants.NameSurnamePropId,
                TypedValue  = new TypedValue {
                    DataType = MFDataType.Text, Value = "Rıza Gökay Kıvırcıoğlu"
                }
            };

            var props = new PropertyValue[] { nameProp, tcknProp };

            request = CreateRequest(updatePropertyPath, "POST", props);
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ExtendedObjectVersion));

            var updatedEmployee = (ExtendedObjectVersion)deserializer.ReadObject(response.GetResponseStream());

            //Check in the employee back to the server
            checkOutType.Value = MFCheckOutStatus.CheckedIn;

            request = CreateRequest(checkOutPath, "POST", checkOutType);
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ObjectVersion));

            var checkecInEmployee = (ObjectVersion)deserializer.ReadObject(response.GetResponseStream());

            #endregion

            #region Create ValueList Item
            var valueListCreatePath = $"{Constants.RestURL}/REST/valuelists/{Constants.JobsValueListId}/items";

            var vlItem = new ValueListItem {
                Name = "Test Değer"
            };

            request = CreateRequest(valueListCreatePath, "POST", vlItem);
            request.Headers["X-Authentication"] = token.Value;

            // Get the response.
            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ValueListItem));

            var valueListResult = (ValueListItem)deserializer.ReadObject(response.GetResponseStream());

            var internalIdOfValueListItem = valueListResult.ID;
            #endregion

            #region Update ValueListItem Title
            var valueListUpdatePath = $"{Constants.RestURL}/REST/valuelists/{Constants.JobsValueListId}/items/{internalIdOfValueListItem}/title?_method=PUT";

            request = CreateRequest(valueListUpdatePath, "POST", "Test Yeni Değer");
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ValueListItem));

            valueListResult = (ValueListItem)deserializer.ReadObject(response.GetResponseStream());

            #endregion

            #region Set ValueListItem ExternalID
            var extValueListId = Guid.NewGuid().ToString("N");

            var data = new RequestData {
                InternalId = internalIdOfValueListItem.ToString(), ObjectTypeId = Constants.JobsValueListId.ToString(), ExternalId = extValueListId
            };

            request = CreateRequest(extensionMethodPath, "POST", data);
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            deserializer = new DataContractJsonSerializer(typeof(ResponseMessage));

            extensionMethodResult = (ResponseMessage)deserializer.ReadObject(response.GetResponseStream());
            #endregion

            #region Get By ExternalId

            // /e is important for referring external id
            var externalEmployeePath  = $"{Constants.RestURL}/REST/Objects/{Constants.EmployeeObjectId}/e{extSystemEmployeeId}";
            var externalValueListPath = $"{Constants.RestURL}/REST/Valuelists/{Constants.JobsValueListId}/items/e{extValueListId}";

            //Get employee
            request = CreateRequest(externalEmployeePath, "GET");
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            deserializer   = new DataContractJsonSerializer(typeof(ObjectVersion));
            employeeResult = (ObjectVersion)deserializer.ReadObject(response.GetResponseStream());

            //Get ValueList Item
            request = CreateRequest(externalValueListPath, "GET");
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            deserializer    = new DataContractJsonSerializer(typeof(ValueListItem));
            valueListResult = (ValueListItem)deserializer.ReadObject(response.GetResponseStream());


            #endregion

            #region Delete Object

            var deletePath = $"{Constants.RestURL}/REST/objects/{Constants.EmployeeObjectId}/{employeeResult.ObjVer.ID}/deleted.aspx?_method=PUT";
            var deleteData = new PrimitiveType <bool>()
            {
                Value = true
            };

            request = CreateRequest(deletePath, "POST", deleteData);
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();



            #endregion

            #region Destroy Object

            var destroyPath = $"{Constants.RestURL}/REST/objects/{Constants.EmployeeObjectId}/{employeeResult.ObjVer.ID}/latest.aspx?_method=DELETE&allVersions=true";

            request = CreateRequest(destroyPath, "POST");
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();


            #endregion

            #region Delete ValueList Item

            var valueListDeletePath = $"{Constants.RestURL}/REST/valuelists/{Constants.JobsValueListId}/items/{internalIdOfValueListItem}?_method=DELETE";

            request = CreateRequest(valueListDeletePath, "POST");
            request.Headers["X-Authentication"] = token.Value;

            response = (HttpWebResponse)request.GetResponse();

            #endregion
        }
示例#4
0
        public ObjectWindowResult ShowNewObjectWindow(IntPtr parentWindow, MFObjectWindowMode mode, ObjectCreationInfo objectCreationInfo)
        {
            vault.MetricGatherer.MethodCalled();

            throw new NotImplementedException();
        }
        private void btn_Upload_Click(object sender, EventArgs e)
        {
            if (client.Authentication == null)
            {
                MessageBox.Show("Please authenticate first.", "M-Files Examples", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var openFileDialog = new OpenFileDialog();

            var result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                //Create File Stream
                var fs = File.Open(openFileDialog.FileName, FileMode.Open);

                //Create Temp File
                var restPath = "/files";

                //Post File
                var uploadInfo = client.Post <UploadInfo>(restPath, fs);
                uploadInfo.Extension = Path.GetExtension(openFileDialog.FileName).Replace(".", "");
                uploadInfo.Title     = openFileDialog.FileName;

                //Create PropertyValues & uploadInfo Lists
                var propertyList = new List <PropertyValue>();
                var uploadInfos  = new List <UploadInfo>();

                uploadInfos.Add(uploadInfo);

                //Class property
                var classProp = new PropertyValue()
                {
                    PropertyDef = 100, TypedValue = new TypedValue()
                    {
                        DataType = MFDataType.Lookup, Lookup = new Lookup()
                        {
                            Version = -1, Item = 2
                        }
                    }
                };
                propertyList.Add(classProp);

                //Name property
                var nameProp = new PropertyValue()
                {
                    PropertyDef = 0, TypedValue = new TypedValue()
                    {
                        DataType = MFDataType.Text, Value = Path.GetFileNameWithoutExtension(openFileDialog.FileName)
                    }
                };
                propertyList.Add(nameProp);

                //Sfd Object
                var sfdProp = new PropertyValue()
                {
                    PropertyDef = 22, TypedValue = new TypedValue()
                    {
                        DataType = MFDataType.Boolean, Value = false
                    }
                };
                propertyList.Add(sfdProp);

                //Create Object Creation Info
                var oci = new ObjectCreationInfo();
                oci.Files          = uploadInfos.ToArray();
                oci.PropertyValues = propertyList.ToArray();

                var restPathForObject = "/objects/0.aspx";

                //Make Post Request
                var createdDocument = client.Post <ObjectVersion>(restPathForObject, oci);

                //Dispose File
                fs.Dispose();

                MessageBox.Show(String.Format("Object Created ID: {0}", createdDocument.ObjVer.ID), "M-Files Examples", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }