how to call multiple function in action? - ajax

I am facing a problem while calling multiple functions through AJAX. What i mainly have to do is to call the different functions through AJAX.
This should be working such that when i try to call those functions, they should be sent a request and the response should be the returned values of those function, but i am getting the error while doing so. Can anyone suggest me how to make it work?
public virtual IQueryable<CardViewModel> ChannelQuery(PageInfo p)
{
var q = from client in my.Clients(0, 0)
join m in db.Channels on client.ClientId equals m.ClientId
join c in db.Contents on m.ChannelId equals c.ContentId
where c.ContentName.Contains(p.Where) || m.ChannelShortDescription.Contains(p.Where) || m.ChannelName.Contains(p.Where)
select new CardViewModel
{
Name = "Channel",
ID = m.ChannelId,
Title = m.ChannelName,
Description = m.ChannelShortDescription,
Pic = new VZDev.ViewModels.Pic { width = 255, height = 170, source = `enter code here`m.ChannelLogo, text = m.ChannelName },
PictureViewTemplate = "_PicBanner",
ShowTools = true
};
return q;
}
public virtual IQueryable<CardViewModel> ContentsQueries(PageInfo p)
{
var query = from content in db.Contents
join clients in my.Clients(0, 0) on content.ClientId equals clients.ClientId
join m in db.Channels on clients.ClientId equals m.ClientId
where content.ContentName.Contains(p.Where) || `enter code here`m.ChannelShortDescription.Contains(p.Where) || m.ChannelName.Contains(p.Where)
select new CardViewModel
{
Name = "Content",
ID = content.ContentId,
Title = content.ContentName,
Description = clients.ResellerName,
Pic = new VZDev.ViewModels.Pic { width = 255, height = 170, source = `enter code here`"None", text = content.ContentName },
PictureViewTemplate = "_PicBanner",
ShowTools = true
};
return query;
}
public ViewResult Advance(PageInfo p)
{
return View(ChannelQuery(p).ToPagedResult(p, "ID Desc"));
}

You can only call one function per AJAX call. If you need Channel and Content data in one request, make a dictionary to hold both sets of values. Something like this:
Dictionary<string,object> data = new Dictionary<string,object>();
data.Add("Channel", ChannelQuery());
data.Add("Content", ContentsQuery());

Related

Set the sourceRange of Data Validation to an array of values

I'm creating a social media outreach tracker. I want to create a drop-down list of the contact name. The problem is that I have two sources of names on two different sheets.
I wrote a script that pulls the names from the two different sources and combines them to a single array.
I was hoping to set the source range as that array.
Here is my code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var castingDirectorsTab = auditionsSheet.getSheetByName("Casting Directors");
var contactsTab = auditionsSheet.getSheetByName("Contacts");
var socialMediaOutreachTab = auditionsSheet.getSheetByName("Social Media Outreach");
var lastRowCD = castingDirectorsTab.getLastRow();
var lastRowContacts = contactsTab.getLastRow();
var activeCell = socialMediaOutreachTab.getActiveCell();
var activeColumn = activeCell.getColumn();
// get data
var castingDirectorNameData = castingDirectorsTab.getRange(2, 1, lastRowCD, 1).getValues();
var contactNameData = contactsTab.getRange(2, 1, lastRowContacts, 1).getValues();
//get name data to a single arrays
var castingDirectorName = [];
castingDirectorNameData.forEach(function(yr) {
castingDirectorName.push(yr[0]);
});
var contactName = [];
contactNameData.forEach(function(yr) {
contactName.push(yr[0]);
});
// get rid of the empty bits in the arrays
for (var x = castingDirectorName.length-1; x > 0; x--) {
if ( castingDirectorName[x][0] === undefined ) {
castingDirectorName.splice( x, 1 )
}
}
for (var x = contactName.length-1; x > 0; x--) {
if ( contactName[x][0] === undefined ) {
contactName.splice( x, 1 )
}
}
//combine two data sources for data validation
var combinedNames = [];
combinedNames.push(castingDirectorName + contactName);
Logger.log (combinedNames);
Logger.log( typeof combinedNames);
// data validation set up and build
if (activeColumn == 1 && auditionsSheet.getName() == "Social Media Outreach") {
var range = auditionsSheet.getRange(activeCell.getRow(), activeColumn +1);
var sourceRange = combinedNames;
setDataValid_(range, sourceRange)
}
}
When I enter a date in Col A on Social Media Outreach, nothing happens in Col 2.
I was using an existing working nested data validation script I have but the sourceRange pulls from a sheet based on the value in the active cell. Here is that code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
// data validation for Auditions Tab Projet Type to Project Details
if (aColumn == 9 && aSheet.getName() == 'Auditions') {
var range = aSheet.getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('RefTables!' + aCell.getValue())
setDataValid_(range, sourceRange)
}
}
For this script when I select from the data validation drop-down, a new data validation comes up in the next col with the appropriate secondary data validation.
So the question is, can the source range be set to an array or do I need to put the names back into my sheet to reference a la the second script.
I've looked through the documentation and searched and can't find an answer. I'm relatively new to GAS and am not sure of all the inner workings of the data validation builder.

how to improve the performance of function which takes almost 1 second in loading time (asp.net mvc 3)

I did a profile tracing to check what functions are taking long times , One of the method takes near 1 second and is called 10+ times and i guess it should be a candidate for review. I have included the method, Can anyone tell me how can it possible be improved.
[NonAction]
private ProductModel.ProductMiscModel PrepareProductMiscModel(Product product)
{
if (product == null)
throw new ArgumentNullException("product");
var model = new ProductModel.ProductMiscModel();
var productVariants = _productService.GetProductVariantsByProductId(product.Id);
var getManufactureImage = _manufacturerService.GetProductManufacturersByProductId(product.Id)
.Select(x =>
{
var m = x.Manufacturer.ToModel();
m.PictureModel.ImageUrl = _pictureService.GetPictureUrl(x.Manufacturer.PictureId, _mediaSetting.ManufacturerThumbPictureSize, true);
m.PictureModel.Title = string.Format(_localizationService.GetResource("Media.Manufacturer.ImageLinkTitleFormat"), m.Name);
m.PictureModel.AlternateText = string.Format(_localizationService.GetResource("Media.Manufacturer.ImageAlternateTextFormat"), m.Name);
return m;
})
.ToList();
model.manufactureName = getManufactureImage;
switch (productVariants.Count)
{
case 0:
{
//var productVariant = productVariants[0];
model.Sku = null;
model.ShowSku = false;
// model.attributeName = 0;
} break;
case 1:
//only one variant
{ var productVariant = productVariants[0];
model.Sku = productVariant.Sku; //null;
model.ShowSku = true;
// model.attributeName = _productAttributeService.GetProductVariantAttributesByProductVariantId(productVariant.Id);
model.productSpecification = _specificationAttributeService.GetProductSpecificationAttributesByProductId(productVariant.Product.Id);
}
break;
}
return model;
}
_manufactureService.GetProductManufactureByProductId
public virtual IList<ProductManufacturer> GetProductManufacturersByProductId(int productId, bool showHidden = false)
{
if (productId == 0)
return new List<ProductManufacturer>();
string key = string.Format(PRODUCTMANUFACTURERS_ALLBYPRODUCTID_KEY, showHidden, productId);
return _cacheManager.Get(key, () =>
{
var query = from pm in _productManufacturerRepository.Table
join m in _manufacturerRepository.Table on
pm.ManufacturerId equals m.Id
where pm.ProductId == productId &&
!m.Deleted &&
(showHidden || m.Published)
orderby pm.DisplayOrder
select pm;
var productManufacturers = query.ToList();
return productManufacturers;
});
}
Use StopWatch in the method to determine which part it is that takes long time.
you might want to include the picture url in the original list instead of traversing each item and call _pictureService.GetPictureUrl.

Error in View when i try use inherit Linq magic

I try make table where i keep children-parent data. Ofc root of parents is "0" and here in table can by many roots. When i try make this work i got error.
Unable to create a constant value of type 'Projekty03.ViewsModels.ParagrafViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root" });
var _paragrafparent2 = from pr in paragrafRepository.All
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragraf = from par in paragrafRepository.All
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa
};
return View(paragraf);
}
I believe is sht wrong with my poor magic LINQ think. How resolve this ?
Ok here is a answer for my own question. Im sure is not a pretty solution but ...
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root", ParagrafCzynny=false, });
var _paragrafparent2 = from pr in paragrafRepository.AllIncluding(paragraf => paragraf.WniosekPodzial)
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa,
ParagrafParent = pr.ParagrafParent,
ParagrafCzynny = pr.ParagrafCzynny,
ParagrafWplyw = pr.ParagrafWplyw,
WniosekPodzialNazwa = pr.WniosekPodzial.WniosekPodzialNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragrafModel = from par in _paragrafparent3
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa,
WniosekPodzialNazwa = par.WniosekPodzialNazwa
};
return View(paragrafModel);
}

Multiple result set from SQL Via LiNQ

I have a stored procedure as
pr___GetArchiveData
Select * from TABLE1
SELECT * FROM TABLE2
SELECT * FROM TABLE 3
I want to get this result set into a dataset. Or access the values of three select queries!!
I have a DBML file in which when i drag and drop the stored procedure generates a code as follows:-
global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.pr___GetArchiveData")]
public ISingleResult<pr___GetArchiveDataResult> pr___GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(DbType="UniqueIdentifier")] System.Nullable<System.Guid> projectID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), projectID);
return ((ISingleResult<pr__Project_pr___GetArchiveData>)(result.ReturnValue));
}
In the code MVC3 Architecture + LINQ i have written a code to get the result set as follows :-
using (HBDataContext hb = new HBDataContext())
{
System.Data.DataSet ds = new System.Data.DataSet();
String connString = connString;
var conn = new System.Data.SqlClient.SqlConnection(connString);
var cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "pr__GetArchiveData";
cmd.Connection.Open();
var mReader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
//var reader = cmd.ExecuteReader();
//using (System.Data.SqlClient.SqlDataReader mReader = cmd.ExecuteReader())
//{
// while (mReader.Read())
//{
// mReader.Read();
var tbl1 = hb.Translate<tbl1 >(mReader).ToList();
// mReader = cmd.ExecuteReader();
mReader.NextResult();
var tbl2 = hb.Translate<tbl2 >(mReader).ToList();
mReader.NextResult();
var tbl3 = hb.Translate<tbl3>(mReader).ToList();
// }
// }
}
But while running it throws error as -
"Invalid attempt to call NextResult when reader is closed."
I am not sure where i am wrong!!
I have tried using it as while
(mReader.Read())
Kindly suggest!!!!
The code gen for ISingleResult won't provide multiple result sets
Try adding your own IMultipleResults wrapper - see the tutorial in http://blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql-and-multiple-result-sets-in-stored-procedures.aspx
In .dbml file for the stored procedure the code will be like
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.pr__Home_GetArchiveData")]
public ISingleResult<pr__Home_GetArchiveData> pr__Home_GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(Name="AlbumID", DbType="UniqueIdentifier")] System.Nullable<System.Guid> albumID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), albumID);
return ((ISingleResult<pr__Album_GetAlbumsFilesResult>)(result.ReturnValue));
}
Replace it with IMultipleResult as below `
[global::System.Data.Linq.Mapping.FunctionAttribute(Name = "dbo.pr__Home_GetArchiveData")]
[ResultType(typeof(tbl1))]
[ResultType(typeof(tbl2))]
[ResultType(typeof(tbl3))]
[ResultType(typeof(tbl4))]
public IMultipleResults pr__Home_GetArchiveData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "HOMEID", DbType = "UniqueIdentifier")] System.Nullable hOMEID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), hOMEID);
return ((IMultipleResults)result.ReturnValue);
}
in the code .
using (HBDataContext hb = new HBDataContext())
{
using (System.Data.Linq.IMultipleResults _results = hb.pr__Home_GetArchiveData(model.HomeID))
{
List<tbl1> _tbl1= _results.GetResult<tbl1>().ToList();
List<tbl2> _tbl2= _results.GetResult<tbl2>().ToList();
List<tbl3> _tbl3= _results.GetResult<tbl3>().ToList();
List<tbl4> _tbl4= _results.GetResult<tbl4>().ToList();}}
You will get the values of the Select queries from theStoredProcedure ...

How to make this LINQ To entity method work when it has Nullable LEFT JOIN

Here is the code snippet, actually the whole method. This method works f,ine when NULLAblE Foreign Key Refernces has value. When the value is not there, then this method does not work. My idea is to get all the records even if the references column is NULL. Here is the code :
public List<PostedJob> GetPostedJobs(int startingIndex, int maximumRows)
{
using (var records = new CommonEvent())
{
var resultSet =
from r in records.ProjectPosts
join rr in records.Categories on r.Category_FK equals rr.ID
join al in records.ApplyForLimits on r.ApplyForLimit_FK
equals al.Id
//from uImage in
// records.UploadedFiles
// .Where(uu=>uu.Id == r.UploadedFileInfo_FK
// || r.UploadedFileInfo_FK == null).DefaultIfEmpty()
join a in records.UploadedFiles on r.UploadedFileInfo_FK
equals a.Id into something
from uImage in something.DefaultIfEmpty()
orderby r.PostId
select new Models.PostedJob
{
ApplyForLimitName = al.Name,
ProjectTitle = r.ProjectTitle,
ProjectDescription = r.ProjectDescription,
ProjectSummaryDescription = r.ProjectSummaryDescription,
SkillsRequirements = r.SkillsRequirements,
CategoryName = rr.CategoryName,
UploadedFileID = (int) r.UploadedFileInfo_FK,
UploadedFileInformation = uImage == null ?
new Models.UploadedFile
{
fileContents = new byte [] { (byte) 0},
FileExtension = string.Empty,
FileName = string.Empty,
FileSize = 0,
UploadedDate = DateTime.Now
}
:
new Models.UploadedFile
{
fileContents = uImage.FileContents,
FileExtension = uImage.FileExtension,
FileName = uImage.FileName,
FileSize = uImage.FileSize,
UploadedDate = DateTime.Now
}
};
return resultSet.Skip(startingIndex).Take(maximumRows).ToList();
}
Thank you for any suggestions or ideas on how to proceed . I am using .NET 4.0
Can you not use the Associations generated for you?
var a = records
.ProjectPosts
.Select(
projectPost =>
new Models.PostedJob()
{
ProjectTitle = projectPost.ProjectTitle,
CategoryName = projectPost.Category.CategoryName,
});
Something along those lines?
EDIT: And just add Null checks when the FK may fail
example:
CategoryName = projectPost.Category == null ? String.Empty : projectPost.Category.CategoryName,

Resources