How do insert a record into a from a string using split function in MVC4? - c#-4.0

Hi all i have a string like this which i am passing an ajax function to my controller action method
Brand1~1001=>undefined_undefined|
Category1~2001=>1001_Brand1|
Category2~2002=>1001_Brand1|
Product3~3003=>2002_Category2|
Product4~3004=>Product3~3003|
Product5~3005=>2002_Category2|
Product6~3006=>2002_Category2|
and i have an Menus table in db i had added that as an entity model to my project
Menus
[MenuID],[MenuName],[ParentID]
and i have model like this
public class MenuItems
{
public List<MenuItems> GetALL { get; set; }
public int MenuId { get; set; }
public string MenuName { get; set; }
public int parentId { get; set; }
}
now i want to split the string i have and insert into the above table like this
[MenuID],[MenuName],[ParentID]
1001 ,Brand1 ,null
2001 ,category1 ,1001
2002 ,category2 ,1001
3003 ,product3 ,2002
3004 ,product4 ,3003
3005 ,product5 ,2002
3006 ,product6 ,2002
in the above string Brand1~1001=>undefined_undefined| here Brand1~1001 is the parentmenu and 1001 is the id of the menu
Category1~2001=>1001_Brand1| and here Category1~2001 is the sub menu of the 1001_Brand1 i think you all got waht i amtrying to do can any one help me here please
what i amtrying
public ActionResult MenuDrag()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
string[] list = m.Split('>');
//stuck from here confused what to do next and how do i insert the data in my accordingly
}
}
return View();
}

You are almost there just replace your post method with this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
MenuItems items = new MenuItems();
//check the string for empty
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
if (m != "")
{
string[] list = m.Split('>');
string[] menu = list[0].Split('~');
string[] parents = list[1].Split('~');
items.MenuItemID = Convert.ToInt16(menu[1]);
items.MenuName = menu[0].ToString();
if (parents[0] == "undefined")
{
items.ParentID = 0;
db.MenuItems.Add(items);
db.SaveChanges();
}
else
{
int parentid=Convert.ToInt16(parents[0]);
var menuid = from me in db.MenusMains where me.MenuItemID == parentid select new { MenuID = me.MenuID };
foreach (var id in menuid)
{
items.ParentID = Convert.ToInt16(id.MenuID);
}
db.MenuItems.Add(items);
db.SaveChanges();
}
}
}
}
return View();
}
}
i had used
if (m != "")
{
}
since u may get an index out of bound exception there since when in your string at this
string[] menus = menustring.Split('|');
u will get an empty ('|') you have to handle this
hope this works

Related

How can i send data from ToolPart1 class to WebPart1 class

I cannot send a array data from ToolPart to WebPart although string data is oke. I debug and know that the statement code webpart.ListColumns[i] = lstBoxSend.Items[i].Value is right and have data but i dont know why property ListColumns in WebPart is null
public class ToolPart1 : Microsoft.SharePoint.WebPartPages.ToolPart
{
public override void ApplyChanges()
{
base.ApplyChanges();
var webpart = (WebPart1)this.ParentToolPane.SelectedWebPart;
webpart.SiteUrl = txtURL.Text;
webpart.ListName = ddlList.SelectedValue;
if (webpart.ListColumns == null)
{
webpart.ListColumns = new string[lstBoxSend.Items.Count];
}
for (int i = 0; i < lstBoxSend.Items.Count; i++)
{
webpart.ListColumns[i] = lstBoxSend.Items[i].Value;
}
}
}
public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart
{
public string SiteUrl { get; set; }
public string ListName { get; set; }
public string[] ListColumns { get; set; }
}
I want receive array data in WebPart From ToolPart
Override ApplyChanges to send data to webpart, check this demo
public override void ApplyChanges()
{
int i = 0;
WebPartCustom1 wpCustom = (WebPartCustom1)this.ParentToolPane.SelectedWebPart;
int.TryParse(_itensToolPart.Text, out i);
wpCustom.MyInt = i;
wpCustom.MyString = _titleToolPart.Text;
wpCustom.MyGuid = _ddlToolPart.SelectedItem.Value;
}

Navigation property is null

Album navigation property is null in SellingRequest when I try to load it by include() while it seems every thing is OK!
These are the codes:
public class Album
{
public int Id { get; set; }
public string Note { get; set; }
public virtual SellingRequest SellingRequest { get; set; }
public int? SellingRequestId { get; set; }
public List<Photo> Photos { get; set; }
public virtual MortgageAndRent MortgageAndRent { get; set; }
public int? MortgageAndRentId { get; set; }
}
public class SellingRequest
{
#region Properies
public int Id { get; set; }
public virtual Album Album { get; set; }
public int AlbumId { get; set; }
#endregion Properies
}
Here is where I create album for SellingRequest.
public ActionResult DoUpload(HttpPostedFileBase file, UploadPopupViewModel uploadPopupViewModel)
{
if (file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Contents/Images"), Path.GetFileName(file.FileName));
file.SaveAs(path);
Photo photo = new Photo() { Path = path };
ResponseMessage<Album> album = new ResponseMessage<Album>();
if(uploadPopupViewModel.SellingRequestId!=0)
album = _albumService.GetAlbumBySellingRequestId(uploadPopupViewModel.SellingRequestId);
if (uploadPopupViewModel.MortgageAndRentId != 0)
album = _albumService.GetAlbumByMortgageAndRentId(uploadPopupViewModel.SellingRequestId);
if (album.IsSuccess)
{
photo.AlbumId = album.Result.Id;
}
else
{
Album newAlbum = new Album();
if (uploadPopupViewModel.SellingRequestId != 0)
newAlbum.SellingRequestId = uploadPopupViewModel.SellingRequestId;
if (uploadPopupViewModel.MortgageAndRentId != 0)
newAlbum.MortgageAndRentId = uploadPopupViewModel.MortgageAndRentId;
ResponseMessage<Album> beingSavedAlbum = _albumService.Insert(newAlbum);
ResponseMessage<SellingRequest> sellingRequest = _sellingRequestService.GetById(uploadPopupViewModel.SellingRequestId);
if(sellingRequest.IsSuccess)
{
sellingRequest.Result.AlbumId = newAlbum.Id;
_sellingRequestService.Update(sellingRequest.Result);
}
if(beingSavedAlbum.IsSuccess)
photo.AlbumId = beingSavedAlbum.Result.Id;
}
ResponseMessage<Photo> beingSavedPhoto = _photoService.Insert(photo);
if (beingSavedPhoto.IsSuccess)
{
return RedirectToAction("UploadPopup", "Photo", uploadPopupViewModel);
}
else
{
ModelState.AddModelError("ImageError", beingSavedPhoto.ErrorMessages[0]);
return View("AddPhoto");
}
}
else
{
ModelState.AddModelError("ImageError", "Please choose a photo.");
return View("AddPhoto");
}
}
}
And Here is where I Try to query:
public IEnumerable<TEntity> GET(Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _context.Set<TEntity>();
if (filter != null)
query = query.Where(filter);
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
query = query.Include(includeProperty);
if (orderBy != null)
return orderBy(query).ToList();
else
return query.ToList();
}
And consequently, Here is where I try to load Album by include.
public List<SellingRequest> GetAllSellingRequests()
{
List<SellingRequest> sellingRequests = _sellingRepository.GET(null, includeProperties: "Address,Album.Photos", orderBy: sR => sR.OrderBy(s => s.RegisteredDate).OrderByDescending(s => s.RegisteredDate)).ToList();
return sellingRequests;
}
With this function I have the Address property but Album is null! It also happens vise versa. I mean when I include the sellingRequest from album, it returns me null, as well! This is while I can include all other entities with no problem!
Edit
This is the schema of my table in database:
SellingRequest Table
And this is the picture of Get.
Any suggestion would be appreciated in advance.
Regards

ServiceStack OrmLite How can I achieve automatic setting of foreign key/related properties?

I have created the following example to test Foreign Keys and up to this point, it works well. What I would like to be able to do, is use this framework that I built to set the property of the relationship and have it Save the child object when the Parent is saved and automatically set the PrimaryKey and Foreign Key.
The DataManager class exposes the Connection
public class DataManager
{
DataManager()
{
OrmLiteConfig.DialectProvider = SqliteDialect.Provider;
ConnectionString = SqliteFileDb;
updateTables();
}
private void updateTables()
{
using (var dbConn = OpenDbConnection())
{
dbConn.DropAndCreateTable<Person>();
dbConn.DropAndCreateTable<PhoneNumber>();
}
}
public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();
private static DataManager manager;
public static DataManager Manager {
get
{
if (manager == null)
manager = new DataManager();
return manager;
}
}
public IDbConnection InMemoryDbConnection { get; set; }
public IDbConnection OpenDbConnection(string connString = null)
{
connString = ConnectionString;
return connString.OpenDbConnection();
}
protected virtual string ConnectionString { get; set; }
protected virtual string GetFileConnectionString()
{
var connectionString = SqliteFileDb;
return connectionString;
}
}
These are my POCO's with the BaseClass used to Achieve my results:
public class Person : LiteBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
private List<PhoneNumber> numbers;
public List<PhoneNumber> PhoneNumbers {
get
{
if (numbers == null)
numbers = GetList<PhoneNumber>(p => p.Person == Id);
return numbers;
}
}
}
public class PhoneNumber
{
public string Number { get; set; }
public string Description { get; set; }
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[References(typeof (Person))]
public int Person { get; set; }
public void AddPerson(Person person)
{
Person = person.Id;
}
}
public class LiteBase:INotifyPropertyChanged
{
public List<T> GetList<T>(Expression< Func<T,bool>> thefunction) where T : new()
{
var objects = new List<T>();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
objects = conn.Where<T>(thefunction);
}
return objects;
}
public T GetItem<T>(Expression<Func<T, bool>> thefunction) where T : new()
{
T obj = new T();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
obj = conn.Where<T>(thefunction).FirstOrDefault<T>();
}
return obj;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Simple Class to Create Person and PhoneNumber objects
public class PersonManager
{
public void CreatePerson(string name, string surname, string number)
{
using (var conn = DataManager.Manager.OpenDbConnection())
{
var pnum = new PhoneNumber { Number = number };
var person = new Person
{
Name=name,
Surname = surname,
};
conn.Save<Person>(person);
var id = conn.GetLastInsertId();
person.Id = (int)id;
pnum.AddPerson(person);
conn.Save<PhoneNumber>(pnum);
}
}
public List<Person> GetPeople()
{
List<Person> people;
using (var conn = DataManager.Manager.OpenDbConnection())
{
people = conn.Select<Person>();
}
return people;
}
public List<PhoneNumber> GetNumbers()
{
List<PhoneNumber> numbers;
using (var conn = DataManager.Manager.OpenDbConnection())
{
numbers = conn.Select<PhoneNumber>();
}
return numbers;
}
}
And here is the usage:
var manager = new PersonManager();
manager.CreatePerson("John", "Doe", "12345679");
manager.CreatePerson("Jack", "Smith", "12345679");
manager.CreatePerson("Peter", "Jones", "12345679");
manager.CreatePerson("Dan", "Hardy", "12345679");
var people = manager.GetPeople();
var numbers = manager.GetNumbers();
for (int i = 0; i < people.Count; i++)
{
Console.WriteLine("{0} {1} {2}",
people[i].Name,people[i].Surname,people[i].Id);
}
for (int n = 0; n < numbers.Count; n++)
{
Console.WriteLine("PN: {0} {1}",
numbers[n].Number,numbers[n].Person);
}
for (int p = 0; p < people.Count; p++)
{
var person = people[p];
Console.WriteLine("{0}: {1} {2} {3}",
person.Id,person.Name,person.Surname,person.GetItem<PhoneNumber>(x=>x.Person==person.Id).Number);
}
The output is as I expected :
John Doe 1
Jack Smith 2
Peter Jones 3
Dan Hardy 4
PN: 12345679 1
PN: 12345679 2
PN: 12345679 3
PN: 12345679 4
1: John Doe 12345679
2: Jack Smith 12345679
3: Peter Jones 12345679
4: Dan Hardy 12345679
What I really would like to be able to do is the following:
var john = new Person
{
Name = "John",
Surname = "Smith",
PhoneNumber = new PhoneNumber { Number = "123456789" }
};
conn.Save<Person>(john);
var number = john.PhoneNumber.Number
Is this at all possible?
By default OrmLite v3 blobs all complex types properties in a string field and you need to explicitly set all references.
In the next major v4 release (ETA late Nov 2013), OrmLite adds some support for external references with the [Reference] attribute, which lets you tell OrmLite these properties should be stored in an external table and not blobbed, e.g:
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public CustomerAddress PrimaryAddress { get; set; }
[Reference]
public List<Order> Orders { get; set; }
}
This will allow you to call db.SaveReferences() to save the reference properties, e.g:
var customer = new Customer
{
Name = "Customer 1",
PrimaryAddress = new CustomerAddress {
AddressLine1 = "1 Humpty Street",
City = "Humpty Doo",
State = "Northern Territory",
Country = "Australia"
},
Orders = new[] {
new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
}.ToList(),
};
Assert.That(customer.Id, Is.EqualTo(0)); //Id is not saved yet
//Inserts customer, populates auto-incrementing customer.Id
//Specify `references:true` to populate the ForeignKey ids and
//save the related rows as well, e.g:
db.Save(customer, references:true);
Assert.That(customer.Id, Is.GreaterThan(0));
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(customer.Id));
Assert.That(customer.Orders.All(x => x.CustomerId == customer.Id));
Saving References manually
For more fine-grained control you can also choose which references you want to save, e.g:
db.Save(customer); //Doesn't save related rows
//1:1 PrimaryAddress Reference not saved yet
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(0));
//1:1 PrimaryAddress Reference saved and ForeignKey id populated
db.SaveReferences(customer, customer.PrimaryAddress);
//1:Many Orders References saved and ForeignKey ids populated
db.SaveReferences(customer, customer.Orders);
Loading all related rows with the entity
You can then load the master row and all its references with db.LoadSingleById, e.g:
var dbCustomer = db.LoadSingleById<Customer>(customer.Id);
dbCustomer.PrintDump();
Assert.That(dbCustomer.PrimaryAddress, Is.Not.Null);
Assert.That(dbCustomer.Orders.Count, Is.EqualTo(2));

Want to navigate contact name to next page

I want to navigate the DisplayName to next page here I paste a code, DisplayName cannot be navigated to next page
this.DisplayedContacts = new ObservableCollection<string>();
this.DataContext = this.DisplayedContacts;
var contacts = new Contacts();
contacts.SearchCompleted += (s, e) =>
{
foreach (var contact in e.Results)
{
this.DisplayedContacts.Add(contact.DisplayName + " - " +
(contact.PhoneNumbers.Any()
? contact.PhoneNumbers.First().PhoneNumber
: string.Empty));
} };
contacts.SearchAsync(string.Empty, FilterKind.DisplayName, null);
}
void MakeCall(bool bWithVideo)
{
NavigationService.Navigate(new Uri(NavigationUri.BuildMakeCallUriString("/CallPage.xaml", DisplayName, bWithVideo), UriKind.Relative));
}
public ObservableCollection<string> DisplayedContacts { get; set; }
private void callcon_Click_1(object sender, RoutedEventArgs e)
{
MakeCall(e.OriginalSource == callcon);
}
public string PhoneNumbers { get; set; }
public string DisplayName { get; set; }
i think you are not making a correct querystring on the MakeCall method.
you can use this
void MakeCall(bool bWithVideo)
{
string QueryString =string.Format("{0},{1}",DisplayName,bWithVideo);
NavigationService.Navigate(new Uri("/CallPage.xaml?q=" + QueryString, UriKind.RelativeOrAbsolute));
}
and on the next page handle NavigationContext
string strCodeTiers = string.Empty;
if (NavigationContext.QueryString.TryGetValue("q", out strCodeTiers))
{
string[] nums = strCodeTiers.Split(',');
string DisplayName = nums[0];
string bWithVideo = nums[1];
bool BWithVideo =Convert.toBool(bWithVideo);
}

C# 4.0 Entity Framework ExecuteStoreQuery:There is already an open DataReader

I use ExecuteStoreQuery and make an IEnumerable<> list. When I get this list with foreach and use some linq query in this area it give a this error :
There is already an open DataReader associated with this Connection which must be closed first.
What must I do for this ?
My code looks like that :
//IEnumerable function
public IEnumerable<NewTable> YirmiAjansTweetList()
{
string nativeSQLQuery = "Select t1.id,t1.baslik,t1.url,t1.gtarih,t3.ck,t3.cs,t2.token,t2.tokensecret from yirmiajanstweets t1 join uyeler t2 ON(t1.uid=t2.u_id) join uygulamalar t3 ON(t2.uyid=t3.u_id) where t1.gtarih is not null and t1.durum=0 and t1.gtarih<Now();";
IEnumerable<NewTable> newList = db.ExecuteStoreQuery<NewTable>(nativeSQLQuery, System.Data.Objects.MergeOption.NoTracking);
if (newList != null)
{
return newList;
}
else
{
return null;
}
}
public class NewTable
{
public int id { get; set; }
public string baslik { get; set; }
public string url { get; set; }
public DateTime gtarih { get; set; }
public string ck { get; set; }
public string cs { get; set; }
public string token { get; set; }
public string tokensecret { get; set; }
}
//look for a record function
public yirmiajanstweets YirmiAjansKayitBak(int _id)
{
yirmiajanstweets ya = db.yirmiajanstweets.FirstOrDefault(f => f.id == _id);
if (ya != null)
{
return ya;
}
else
{
return null;
}
}
//i get this list like that with foreach
IEnumerable<dynamic> ya = yaBLL.YirmiAjansTweetList().AsEnumerable();
if (ya != null)
{
foreach (var item in ya)
{
//when read this line give error
var myRecord = YirmiAjansKayitBak(item.id);
}
}
else
{
Response.Write("Not found !");
}
Try to add MultipleActiveResultSets=true to your connection string.
Try to load the query result into a list before you iterate over the collection:
IEnumerable<dynamic> ya = yaBLL.YirmiAjansTweetList().ToList();

Resources