protected void Page_Load(object sender, EventArgs e)
        {
            _configurationCloud = new ApiConfiguration(SessionManager.DeveloperKey, SessionManager.DeveloperSecret, SessionManager.CallBackUrl);
            _oAuthKeyService    = new OAuthKeyService();
            if (_oAuthKeyService.OAuthResponse == null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Server.MapPath("~/info.xml"));

                XmlNode nodeObj = doc.SelectSingleNode("/user/code");
                //string id = nodeObj["Project"].InnerText; // For inner text


                var oauthService = new MYOB.AccountRight.SDK.Services.OAuthService(_configurationCloud);
                _oAuthKeyService.OAuthResponse = oauthService.GetTokens(nodeObj.Attributes["value"].Value);
            }

            SessionManager.MyOAuthKeyServiceAutoBackup = _oAuthKeyService;
            SessionManager.MyConfigurationAutoBackup   = _configurationCloud;

            var cfsCloud = new MYOB.AccountRight.SDK.Services.CompanyFileService(_configurationCloud, null, _oAuthKeyService);

            CompanyFile[] companyFiles = cfsCloud.GetRange();
            CompanyFile   companyFile  = companyFiles.FirstOrDefault(a => a.Id == Guid.Parse(SessionManager.CompanyId));

            SessionManager.SelectedCompanyFileAutoBackup = companyFile;
            ICompanyFileCredentials credentials = new CompanyFileCredentials(SessionManager.CompanyUserId, SessionManager.CompanyPassword);

            SessionManager.MyCredentialsAutoBackup = credentials;
            HandleSales();
            HandlePurchase();
        }
Exemple #2
0
        public async Task <ActionResult> Create([Bind(Include = "CompanyName,CompanyLink,Address,City,State,ZipCode,Latitude,Longitude,CareerPage,CompanyType,IndustryServed,LanguagesUsed,Files")] Company company, HttpPostedFileBase upload)
        {
            var _company = db.Companies.Find(company.CompanyName);

            if (_company != null)
            {
                ViewBag.ErrorMessage = company.CompanyName + " already exists.";
            }
            else if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var logo = new CompanyFile
                    {
                        FileName    = System.IO.Path.GetFileName(upload.FileName),
                        FileType    = FileType.Logo,
                        ContentType = upload.ContentType,
                        CompanyName = company.CompanyName
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        logo.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    company.Files = new List <CompanyFile> {
                        logo
                    };
                }
                db.Companies.Add(company);
                await db.SaveChangesAsync();

                return(RedirectToAction("Details", new { id = company.CompanyName }));
            }

            return(View(company));
        }
Exemple #3
0
 /// <summary>
 /// Save/Update a photo of an entity
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="uid">The identifier of the entity to retrieve</param>
 /// <param name="photoData">The image binary</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="onComplete">The action to call when the operation is complete</param>
 /// <param name="onError">The action to call when the operation has an error</param>
 public virtual void SavePhoto(CompanyFile cf, Guid uid, byte[] photoData, ICompanyFileCredentials credentials, Action <HttpStatusCode, string> onComplete, Action <Uri, Exception> onError)
 {
     MakeApiPutRequestDelegate(BuildUri(cf, uid, "/Photo"), new Photo()
     {
         Data = photoData
     }, credentials, onComplete, onError);
 }
Exemple #4
0
 /// <summary>
 /// Save/Update a photo of an entity
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="uid">The identifier of the entity to retrieve</param>
 /// <param name="photoData">The image binary</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <returns></returns>
 public virtual string SavePhoto(CompanyFile cf, Guid uid, byte[] photoData, ICompanyFileCredentials credentials)
 {
     return(MakeApiPutRequestSync(BuildUri(cf, uid, "/Photo"), new Photo()
     {
         Data = photoData
     }, credentials));
 }
Exemple #5
0
        private void DgvCompanyFilesCellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //Get the selected company file
            CompanyFile companyFile = ((CompanyFile[])dgvCompanyFiles.DataSource)[e.RowIndex];

            //Get configuration that matches server where file is
            IApiConfiguration config = companyFile.Uri.GetLeftPart(UriPartial.Path).ToLower().Contains(LocalApiUrl)
                                           ? _configurationLocal
                                           : _configurationCloud;

            //Get the credentials for the database
            var frmLogin = new LoginForm();

            frmLogin.ShowDialog(this);
            if (frmLogin.Username.Length <= 0)
            {
                return;
            }
            ICompanyFileCredentials credentials = new CompanyFileCredentials(frmLogin.Username, frmLogin.Password);

            ////load the Invoice List
            //var frmInvoiceList = new InvoiceListForm();
            //frmInvoiceList.Initialise(config, companyFile, credentials, _oAuthKeyService);
            //frmInvoiceList.Show();
        }
        // Route depends on Layout and UID which is not in the entity by default
        private Uri BuildUri(CompanyFile companyFile, BillAttachmentsData entity, string queryString = null)
        {
            // Building up nested routes to support multiple resource types
            var route = $"Purchase/Bill/{entity.BillLayout}/";

            return(UriHelper.BuildUri(companyFile, route, entity.BillUID, "/Attachment", queryString));
        }
Exemple #7
0
        public void DeleteAsync_Overloads_Call_Through_Correctly()
        {
            var cf          = new CompanyFile();
            var id          = Guid.NewGuid();
            var credentials = Substitute.For <ICompanyFileCredentials>();
            var errorLevel  = ErrorLevel.WarningsAsErrors;
            var ret         = Task.FromResult("");

            var callCount = 0;

            var testMutableService = new MutableServiceTestClass <BaseEntity>(Substitute.For <IApiConfiguration>(), Substitute.For <IWebRequestFactory>(), Substitute.For <IOAuthKeyService>())
            {
                DeleteAsyncCallback =

                    (_cf, _id, _credentials, _errorLevel, _cancellationToken) =>
                {
                    callCount++;
                    Assert.AreEqual(cf, _cf);
                    Assert.AreEqual(id, _id);
                    Assert.AreEqual(errorLevel, _errorLevel);
                    Assert.AreEqual(_cancellationToken, CancellationToken.None);

                    return(ret);
                }
            };


            var _ret = testMutableService.DeleteAsync(cf, id, credentials, errorLevel);

            Assert.AreEqual(1, callCount);
            Assert.AreEqual(_ret, ret);
        }
Exemple #8
0
        // <summary>
        /// This public method may be very long running, so it returns a Task which allows calling
        /// application to 'await' the asynchronous return of a future result (or an exception).
        /// </summary>
        /// <remarks>
        ///     This is an example of a public library method that may run for a long time
        ///     By passing a CancellationToken we can test if the caller wants us to cancel.
        ///     By passing an IProgress we can pass information back to the caller (conveniently it
        ///     happens on the original thread if the caller is a Forms or WPF app).
        /// </remarks>
        public void PrepareToCommunicateWithMyob(string MYOBLogin)
        {
            //http://stackoverflow.com/questions/11879967/best-way-to-convert-callback-based-async-method-to-awaitable-task


            var developerKey = ConfigurationManager.AppSettings["MyobDeveloperKey"];


            var developerSecret = ConfigurationManager.AppSettings["MyobDeveloperSecret"];

            _configurationCloud = new ApiConfiguration(developerKey, developerSecret, "http://desktop");

            // you many get a benign error here on the fist time - if the tokens have not been stored
            try
            {
                TryGetTokens();
            }
            catch (Exception)
            {
                try
                {
                    TryGetTokens();
                }
                catch (Exception)
                {
                    throw;
                }
            }

            var task2        = GetCompanyFiles(_configurationCloud, _oAuthKeyService);
            var companyFiles = task2.Result; // waits for the files

            _companyFile = companyFiles.First();
            _credentials = AskForCredentials(_companyFile, MYOBLogin);
        }
Exemple #9
0
        /// <exclude />
        // Examples:
        // baseUrl/Banking/SpendMoney/spendMoneyUid/Attachment/attachmentUid
        // baseUrl/Banking/SpendMoney/spendMoneyUid/Attachment
        public Uri BuildUri(CompanyFile companyFile, Guid spendMoneyUid, Guid?attachmentUid = null, string queryString = null)
        {
            var qs       = string.IsNullOrEmpty(queryString) ? string.Empty : queryString;
            var attchUid = attachmentUid.HasValue ? "/" + attachmentUid.ToString() : string.Empty;

            return(new Uri(string.Format("{0}/{1}/{2}{3}{4}{5}", companyFile.Uri, "Banking/SpendMoney", spendMoneyUid.ToString(), "/Attachment", attchUid, qs)));
        }
Exemple #10
0
 /// <summary>
 /// Retrieve an entity
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="financialYear">The requested financial year</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="onComplete">The action to call when the operation is complete</param>
 /// <param name="onError">The action to call when the operation has an error</param>
 /// <param name="eTag">The <see cref="BaseEntity.ETag" /> from a previously fetched entity</param>
 public void Get(CompanyFile cf, int financialYear,
                 ICompanyFileCredentials credentials, Action <HttpStatusCode, AccountBudget> onComplete,
                 Action <Uri, Exception> onError, string eTag = null)
 {
     MakeApiGetRequestDelegate(BuildUri(cf, financialYear), credentials, onComplete,
                               onError, eTag);
 }
Exemple #11
0
 /// <summary>
 /// Save/Update a photo of an entity
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="uid">The identifier of the entity to retrieve</param>
 /// <param name="photoData">The image binary</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public Task <string> SavePhotoAsync(CompanyFile cf, Guid uid, byte[] photoData, ICompanyFileCredentials credentials, CancellationToken cancellationToken)
 {
     return(this.MakeApiPutRequestAsync(this.BuildUri(cf, uid, "/Photo"), new Photo()
     {
         Data = photoData
     }, credentials, cancellationToken));
 }
        /// <summary>
        /// Delete an Attachment
        /// </summary>
        /// <param name="cf">A company file that has been retrieved</param>
        /// <param name="uri">Uri of the Thumbnail from the Get response</param>
        /// <param name="credentials">The credentials to access the company file</param>
        /// <param name="errorLevel">Treat warnings as errors</param>
        public void Delete(CompanyFile cf, string uri, ICompanyFileCredentials credentials, ErrorLevel errorLevel = ErrorLevel.IgnoreWarnings)
        {
            var queryString = GenerateQueryString(errorLevel);
            var deleteUri   = new Uri(string.Format("{0}{1}", uri, queryString));

            MakeApiDeleteRequestSync(deleteUri, credentials);
        }
Exemple #13
0
 /// <exclude/>
 static Uri ValidateUri(CompanyFile cf, Uri uri)
 {
     if (!uri.AbsoluteUri.ToLowerInvariant().StartsWith(cf.Uri.AbsoluteUri.ToLowerInvariant()))
     {
         throw new ArgumentException("The supplied Uri is not valid for the company file.", "uri");
     }
     return(uri);
 }
Exemple #14
0
        public async t.Task <int> Addtems(CompanyFile myCompanyFile, string pageFilter, CompanyFileCredentials myCredentials, CancellationToken ct)
        {
            var tpc      = _myService.GetRangeAsync(myCompanyFile, pageFilter, myCredentials, ct, null);
            var newItems = await tpc;

            items.AddRange(newItems.Items);
            return(newItems.Items.Count());
        }
Exemple #15
0
 /// <summary>
 /// Retrieve a paged list of entities
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="queryString">An odata filter</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="eTag">The <see cref="BaseEntity.ETag" /> from a previously fetched entity</param>
 /// <returns></returns>
 public PagedCollection <AccountBudget> GetRange(CompanyFile cf, string queryString,
                                                 ICompanyFileCredentials credentials, string eTag = null)
 {
     return
         (MakeApiGetRequestSync <PagedCollection <AccountBudget> >(
              BuildUri(cf, null, queryString == null ? null : "?" + queryString.TrimStart('?')),
              credentials, eTag));
 }
 public void Setup()
 {
     _companyFile = new CompanyFile {
         Id = Guid.NewGuid(),
     };
     _companyFile.Uri = new Uri("https://api.myob.com/accountright/" + _companyFile.Id);
     _route           = "route";
 }
Exemple #17
0
 /// <summary>
 /// Retrieve a paged list of entities
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="queryString">An odata filter</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="onComplete">The action to call when the operation is complete</param>
 /// <param name="onError">The action to call when the operation has an error</param>
 /// <param name="eTag">The <see cref="BaseEntity.ETag" /> from a previously fetched entity</param>
 public void GetRange(CompanyFile cf, string queryString, ICompanyFileCredentials credentials,
                      Action <HttpStatusCode, PagedCollection <AccountBudget> > onComplete,
                      Action <Uri, Exception> onError, string eTag = null)
 {
     MakeApiGetRequestDelegate(
         BuildUri(cf, null, queryString == null ? null : "?" + queryString.TrimStart('?')), credentials,
         onComplete, onError, eTag);
 }
Exemple #18
0
 /// <summary>
 /// Retrieve a paged list of entities
 /// </summary>
 /// <param name="cf">A company file that has been retrieved</param>
 /// <param name="queryString">An odata filter</param>
 /// <param name="credentials">The credentials to access the company file</param>
 /// <param name="cancellationToken"></param>
 /// <param name="eTag">The <see cref="BaseEntity.ETag" /> from a previously fetched entity</param>
 /// <returns></returns>
 public Task <PagedCollection <AccountBudget> > GetRangeAsync(CompanyFile cf, string queryString,
                                                              ICompanyFileCredentials credentials,
                                                              CancellationToken cancellationToken, string eTag = null)
 {
     return
         (this.MakeApiGetRequestAsync <PagedCollection <AccountBudget> >(
              this.BuildUri(cf, null, queryString.Maybe(_ => "?" + _.TrimStart('?'))), credentials,
              cancellationToken, eTag));
 }
        private Uri BuildUri(CompanyFile companyFile, SaleEmail entity)
        {
            /*building up nested route to support multiple resource types
             *  Sale/Invoice/Service/{UID}/email and Sale/Quote/Item/{UID}/email
             */
            var route = "Sale/" + entity.ResourceType + "/" + entity.LayoutType + "/";

            return(UriHelper.BuildUri(companyFile, route, entity.EntityUid, "/Email"));
        }
Exemple #20
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            CompanyFile companyFile = (CompanyFile)CompanyFiles.FirstOrDefault(a => a.Id == Guid.Parse(lblID.Text));//[e.RowIndex];

            ICompanyFileCredentials credentials = new CompanyFileCredentials(txtUserName.Text, txtPassword.Text);

            SessionManager.SelectedCompanyFile = companyFile;
            SessionManager.MyCredentials       = credentials;
            Response.Redirect("SearchPage.aspx");
        }
Exemple #21
0
        /// <summary>
        /// Update an existing entity
        /// </summary>
        /// <param name="cf">A company file that has been retrieved</param>
        /// <param name="entity">The entity to update</param>
        /// <param name="credentials">The credentials to access the company file</param>
        /// <param name="onComplete">The action to call when the operation is complete</param>
        /// <param name="onError">The action to call when the operation has an error</param>
        /// <param name="errorLevel"></param>
        public void Update(CompanyFile cf, AccountBudget entity, ICompanyFileCredentials credentials,
                           Action <HttpStatusCode, string> onComplete, Action <Uri, Exception> onError,
                           ErrorLevel errorLevel = ErrorLevel.IgnoreWarnings)
        {
            var queryString = QueryStringFromErrorLevel(errorLevel);

            MakeApiPutRequestDelegate(
                BuildUri(cf, entity.FinancialYear, extraQueryString: queryString),
                entity, credentials, onComplete, onError);
        }
Exemple #22
0
        /// <summary>
        /// Update an existing entity
        /// </summary>
        /// <param name="cf">A company file that has been retrieved</param>
        /// <param name="entity">The entity to update</param>
        /// <param name="credentials">The credentials to access the company file</param>
        /// <param name="errorLevel"></param>
        /// <returns></returns>
        public string Update(CompanyFile cf, AccountBudget entity, ICompanyFileCredentials credentials,
                             ErrorLevel errorLevel = ErrorLevel.IgnoreWarnings)
        {
            var queryString = QueryStringFromErrorLevel(errorLevel);

            return
                (MakeApiPutRequestSync(
                     BuildUri(cf, entity.FinancialYear,
                              extraQueryString: queryString), entity, credentials));
        }
 private Uri BuildUri(CompanyFile cf, Guid invoiceUid, string template, string title)
 {
     if (string.IsNullOrEmpty(title))
     {
         return(BuildUri(cf, invoiceUid, queryString: string.Format("templatename={0}", template)));
     }
     else
     {
         return(BuildUri(cf, invoiceUid, queryString: string.Format("templatename={0}&title={1}", template, title)));
     }
 }
Exemple #24
0
        /// <summary>
        /// Update an existing entity
        /// </summary>
        /// <param name="cf">A company file that has been retrieved</param>
        /// <param name="entity">The entity to update</param>
        /// <param name="credentials">The credentials to access the company file</param>
        /// <param name="errorLevel"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <string> UpdateAsync(CompanyFile cf, AccountBudget entity, ICompanyFileCredentials credentials,
                                         CancellationToken cancellationToken,
                                         ErrorLevel errorLevel = ErrorLevel.IgnoreWarnings)
        {
            var queryString = QueryStringFromErrorLevel(errorLevel);

            return
                (this.MakeApiPutRequestAsync(
                     this.BuildUri(cf, entity.FinancialYear,
                                   extraQueryString: queryString), entity, credentials, cancellationToken));
        }
Exemple #25
0
 public void InitService(
     CompanyFile companyFile,
     CompanyFileCredentials credentials,
     ApiConfiguration myConfiguration,
     OAuthKeyService myOAuthKeyService)
 {
     myCompanyFile     = companyFile;
     myCredentials     = credentials;
     myService         = new ItemOrderService(myConfiguration, null, myOAuthKeyService);
     myCustomerService = new CustomerService(myConfiguration, null, myOAuthKeyService);
 }
Exemple #26
0
        public ActionResult Edit(CompanyFileVM model)
        {
            if (model.CompanyFile == null)
            {
                model.CompanyFile = new CompanyFile();
            }
            model.UploadFile = CompanyFiles.GetUploadFile(Request.Files[0]);
            if (!FluentValidate(model))
            {
                return(RedirectBack());
            }


            CompanyFile companyFile = null;

            if (model.CompanyFile.Name.IsEmpty())
            {
                model.CompanyFile.Name = model.UploadFile.Name;
            }
            if (model.IsNew)
            {
                companyFile             = model.CompanyFile;
                companyFile.UserID      = User.UserID;
                companyFile.SysFileName = model.UploadFile.Name;
                CompanyFileService.InsertAndSubmit(companyFile);
            }
            else
            {
                var userFileId = model.CompanyFile.Id;
                companyFile = CompanyFileService.GetByPK(userFileId);
                if (companyFile.UserID != User.UserID)
                {
                    throw new NotOwnerException("File");
                }
                companyFile.Update(model.CompanyFile, x => x.Name, x => x.CompanyID);

                if (!model.UploadFile.IsEmpty)
                {
                    companyFile.SysFileName = model.UploadFile.Name;
                }


                CompanyFileService.SubmitChanges();
            }

            if (!model.UploadFile.IsEmpty)
            {
                CompanyFiles.DeleteFile(companyFile.Id);
                var hpf = Request.Files[0];
                hpf.SaveAs(CompanyFiles.GetUserFileSys(companyFile.Id, model.UploadFile.Name));
            }

            return(RedirectToAction(() => List()));
        }
        public void Initialise(IApiConfiguration configuration, CompanyFile companyFile,
                               ICompanyFileCredentials credentials, IOAuthKeyService oAuthKeyService)
        {
            // Add any initialization after the InitializeComponent() call.
            MyConfiguration   = configuration;
            MyCompanyFile     = companyFile;
            MyCredentials     = credentials;
            MyOAuthKeyService = oAuthKeyService;

            Text = string.Format("{0} - {1}", companyFile.Name, companyFile.Uri);
        }
Exemple #28
0
        public void InitService(
            CompanyFile companyFile,
            SDK.CompanyFileCredentials credentials,
            SDK.ApiConfiguration myConfiguration,
            OAuthKeyService myOAuthKeyService)
        {
            myCompanyFile = companyFile;
            myCredentials = credentials;

            myService = new ItemBillService(myConfiguration, null, myOAuthKeyService);
        }
Exemple #29
0
 private void OnComplete(HttpStatusCode statusCode, CompanyFile[] companyFiles)
 {
     for (int i = 0; i < companyFiles.Count(); i++)
     {
         if (companyFiles[i].Name == CompanyName)
         {
             CompanyFile = companyFiles[i];
             break;
         }
     }
     LogintoCompanyFile();
 }
Exemple #30
0
        public async Task ReplaceTextInFile(string fileName)
        {
            FileInfo    fileInfo = new FileInfo(fileName);
            CompanyFile file     = FileFactory.GetInstance(fileInfo.Extension);

            if (file != null)
            {
                file.Load(fileInfo.FullName);
                file.ReplaceText(TargetString, ReplaceString);
                file.Save(fileInfo.FullName);
            }
        }