I am using the 'j0k3r/php-imgur-api-client' package in my laravel project.
The installation of it seems to be good and lucky.
And I wrote a test seeder script(UnitTestSeeder.php) and a class (ImgurClient.php) as followed:
<?php
use Illuminate\Database\Seeder;
use App\Libs\Service\ImgurClient;
class UnitTestSeeder extends Seeder{
public function run(){
$username = 'your_imgur_username';
$id = 'Iemhfpo';
//$response = $this->galleryFavorites($username);//run ok
//$response = $this->favorites($username);// run ok
//$response = $this->randomGalleryImages();//run ok
//$response = $this->uploadImage();//run error
//$response = $this->createAlbum();//run error
print_r($response);
}
private function uploadImage(){
$client = new ImgurClient();
$fpath = storage_path('app/public/test.jpg');
$imageData = ['image' => $fpath, 'type' => 'file'];
return $client->upload($imageData);
}
private function createAlbum(){
$client = new ImgurClient();
$album_data = [];
$album_data['title'] = 'Bracelet';
$album_data['description'] = 'Beautiful Bracelet';
$album_data['privacy'] = 'public';
$album_data['layout'] = 'grid';
return $client->createAlbum($album_data);
}
private function randomGalleryImages(){
$client = new ImgurClient();
return $client->randomGalleryImages();
}
private function galleryFavorites($username){
$client = new ImgurClient();
return $client->galleryFavorites($username);
}
private function favorites($username){
$client = new ImgurClient();
return $client->favorites($username);
}
But saddly, as the code comments showed above,
Some API calls can't work and some other API calls work well.
The 2 calls(createAlbum and uploadImage) throwed exceptions like this
Please view my screenshot here
Anybody have encountered such errors? Thanks all!
Related
Example: I have repository A inside __construct(repo B, repo C) and I want make unit test for function inside repo A but inside it has call b->func_b1 and C->func_c1, how to make? thank you so much!
#Repo A
public function __construct(
CandidateStepMasterInterface $stepMasterRepo,
CandidateProcessInterface $processRepo,
CandidateInterface $candidateRepo
) {
parent::__construct();
$this->stepMasterRepo = $stepMasterRepo;
$this->processRepo = $processRepo;
$this->candidateRepo = $candidateRepo;
}
I make unit test for func here
public function funcA($itemExample) {
//code here
$processes = $this->stepMasterRepo->func_b1();
$dataProcess = $this->processRepo->func_c1($itemExample);
$result = $this->candidateRepo->func_d1($itemExample);
// code here
return $result
}
Unit test file
protected function setUp(): void
{
$this->stepMasterRepo = m::mock(CandidateStepMasterInterface::class)->makePartial();
$this->processRepo = m::mock(CandidateProcessInterface::class)->makePartial();
$this->candidateRepo = m::mock(CandidateInterface::class)->makePartial();
$this->candidatePhaseMasterMock = m::mock(CandidatePhaseMasterRepository::class)->makePartial();
$this->candidatePhaseMasterRepo = new CandidatePhaseMasterRepository(
$this->stepMasterRepo,
$this->processRepo,
$this->candidateRepo,
);
parent::setUp(); // TODO: Change the autogenerated stub
}
public function test_funcA() {
$dataExample = [];
$result = $this->candidatePhaseMasterRepo->funcA(1);
$this->assertEquals($dataExample, $result);
}
Run unit test:::
Mockery\Exception\BadMethodCallException: Received Mockery_0_App_Repositories_SaltCrm_Interfaces_CandidateStepMasterInterface::func_b1(), but no expectations were specified
I have this application in C# on VS2012, in which I need to generate Crystal Report 13.0.x. This application has been running fine for last 2 years or so . Recently did some addons and after that its giving error
Load Report Fail
However strange thing is that , in a day around 100 times this Crystal report is generated and in between it gives out that error. After the whole application has to be exited and then it works fine too. Because of this I am not abel to replicate the error at me end.
Here my code:
public partial class ChangeOrderList : Form
{
ConnectionClass connectionclass = new ConnectionClass();
NewOrderBL NObl = new NewOrderBL();
DailySalesReportBL DSRbl = new DailySalesReportBL();
public ChangeOrderList()
{
InitializeComponent();
}
private void ChangeOrderList_Load(object sender, EventArgs e)
{
/////////////////////////To count Lunch Buffet///////////////////
DataTable dtlb = DSRbl.selectBuffet(DateTime.Today.Date.ToString(), DateTime.Today.Date.ToString());
string date = dtlb.Rows[0][0].ToString();
////////////////////////////////////////////////////////////////
try
{
string sqlqry = "Select KOTNo,TableNo,WaiterName,ItemCode,ItemName,Quantity,Status,Foodtype from tblOrderChange where KOTNo=#kotno and Quantity>'0.00' and (Category!='Appetizer' and Category!='Indian Breads' and Category!='Desserts' and Category!='Beverages' and Category!='Tandoori')";
SqlCommand cmd = new SqlCommand(sqlqry, connectionclass.con);
cmd.Parameters.AddWithValue("#kotno", NewOrderBL.KOTNo);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet1 ds = new DataSet1();
adapter.Fill(ds, "tblOrderChange");
if (ds.Tables["tblOrderChange"].Rows.Count == 0)
{
MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (deliverybl.order == "Delivery")
{
//PrintDelivery printorder = new PrintDelivery();
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
printorder.SetDataSource(ds);
crystalReportViewer1.ReportSource = printorder;
System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
printorder.PrintOptions.PrinterName = printDocument.PrinterSettings.PrinterName;
printorder.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printorder.PrintToPrinter(1, false, 0, 0);
}
else
{
crystalReportViewer1.RefreshReport();
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "LBqty";
paramDiscreteValue.Value = date;
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);
PrintChangeOrderList printchangeorder = new PrintChangeOrderList();
printchangeorder.SetDataSource(ds);
printchangeorder.SetParameterValue("LBqty", date);
crystalReportViewer1.ReportSource = printchangeorder;
System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
printchangeorder.PrintOptions.PrinterName = printDocument.PrinterSettings.PrinterName;
printchangeorder.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printchangeorder.PrintToPrinter(1, false, 0, 0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { connectionclass.disconnect(); }
onlinebl.crystalreport = "";
this.DialogResult = DialogResult.OK;
}
private void btnExit_Click(object sender, EventArgs e)
{
onlinebl.crystalreport = "";
this.DialogResult = DialogResult.OK;
}
I have been banging my head for long . Every where I search it says about the path and I am not using the path anywhere so not able to understand where the fault is.
If you need any more info or the code please let me know. Thanks
Check your class:
<pre>
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
printorder.SetDataSource(ds);
crystalReportViewer1.ReportSource = printorder;
this one has a report Path hidding i guess
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
</pre>
I just deleted internet temp files and after that client has not yet complained about the error. So I am keeping an eye on it if it resolved the issue
I am trying to create a class dynamically based on a base class type.
Below is the code which causing problem
TypeBuilder tb = DynamicType.CreateType(DynamicType.modBuilder, typeof(ResultViewModelVersioned).ToString());
The function for create type is as follow
public static TypeBuilder CreateType(ModuleBuilder modBuilder, string typeName)
{
TypeBuilder typeBuilder = modBuilder.DefineType(typeName,
TypeAttributes.Public );
return typeBuilder;
}
But i am getting com exception _COMPlusExceptionCode -532462766 while defining type in above function.
Here is my function which creates dynamic object
public object GetViewModel<TresultType, TviewModelType>(TresultType result, TviewModelType ViewModel)
{
if (DynamicType.asmBuilder == null)
DynamicType.GenerateAssemblyAndModule();
var finalType = DynamicType.modBuilder.GetType("Beacon11");
TypeBuilder tb = DynamicType.CreateType(DynamicType.modBuilder, ViewModel.GetType().ToString());
tb.SetParent(typeof(ResultViewModelVersionable));
var sourceType = result.GetType();
var targetType = tb.GetType();
foreach (var property in sourceType.GetProperties())
{
var targetProperty = targetType.GetProperty(property.Name);
if (targetProperty == null)
{
DynamicType.CreateProperty(tb, property.Name, property.GetType());
}
}
finalType = tb.CreateType();
var Methods = tb.GetMethods();
Object obj = Activator.CreateInstance(finalType);
return obj;
}
I got code to create DynamicType From the below link
http://geekswithblogs.net/rgupta/archive/2008/12/01/dynamically-creating-types-using-reflection-and-setting-properties-using-reflection.emit.aspx
Any help would be greatly appreciated. If you need any further information please let me know.
I want to post some request values alongside the multipart-formdata file contents. In the old API you could use PostFileWithRequest:
[Test]
public void Can_POST_upload_file_using_ServiceClient_with_request()
{
IServiceClient client = new JsonServiceClient(ListeningOn);
var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath());
var request = new FileUpload{CustomerId = 123, CustomerName = "Foo"};
var response = client.PostFileWithRequest<FileUploadResponse>(ListeningOn + "/fileuploads", uploadFile, request);
var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd();
Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
Assert.That(response.Contents, Is.EqualTo(expectedContents));
Assert.That(response.CustomerName, Is.EqualTo("Foo"));
Assert.That(response.CustomerId, Is.EqualTo(123));
}
I can't find any such method in the new API, nor any overrides on client.Post() which suggest that this is still possible. Does anyone know if this is a feature that was dropped?
Update
As #Mythz points out, the feature wasn't dropped. I had made the mistake of not casting the client:
private IRestClient CreateRestClient()
{
return new JsonServiceClient(WebServiceHostUrl);
}
[Test]
public void Can_WebRequest_POST_upload_binary_file_to_save_new_file()
{
var restClient = (JsonServiceClient)CreateRestClient(); // this cast was missing
var fileToUpload = new FileInfo(#"D:/test/test.avi");
var beforeHash = this.Hash(fileToUpload);
var response = restClient.PostFileWithRequest<FilesResponse>("files/UploadedFiles/", fileToUpload, new TestRequest() { Echo = "Test"});
var uploadedFile = new FileInfo(FilesRootDir + "UploadedFiles/test.avi");
var afterHash = this.Hash(uploadedFile);
Assert.That(beforeHas, Is.EqualTo(afterHash));
}
private string Hash(FileInfo file)
{
using (var md5 = MD5.Create())
{
using (var stream = file.OpenRead())
{
var bytes = md5.ComputeHash(stream);
return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
}
}
}
None of the old API was removed from the C# Service Clients, only new API's were added.
The way you process an uploaded file inside a service also hasn't changed.
Heres some example code. I successfully figured out how to compile this. I grabbed the location and was able to use visual studios object browser to look through the DLL. I cant figure out how to get a class instance and call a function.
public static void test()
{
JScriptCodeProvider js = new JScriptCodeProvider();
System.CodeDom.Compiler.CompilerParameters param = new System.CodeDom.Compiler.CompilerParameters();
var cr = js.CompileAssemblyFromSource(param, new string[] { "package pkg { class b { public function increment(x) { return x+1; } } }" });
foreach (var e in cr.Errors) {
var s = e.ToString();
}
var asm = cr.CompiledAssembly;
var module = cr.CompiledAssembly.GetModules();
//or var module = cr.CompiledAssembly.GetModule("JScript Module");
//...
}
Hmmm realy late on the answer but this is how you would invoke a method from a CodeDom compiled class
You have to use reflection to create an assembly from your compiler results...(your var cr)
Assembly assembly = cr.CompiledAssembly;
Then you have to create an instance of the class you want
object sourceClass = assembly.CreateInstance("YourNamespace.YourClass");
Then you invoke any method inside the class
var result = sourceClass.GetType().InvokeMember("YourMethod", BindingFlags.InvokeMethod, null, sourceClass, new object[] { *Parameters go here* });
And with that what ever the method you invoked had to returned would now be the value of the "result" var....pretty easy.